A place to keep and find your hints on Python use.
Possible Links for Training and Reference
- https://automationstepbystep.com/ (Selenium Reference)
- python – m pip install selenium
- https://codemy.com/ (multiple courses)
- https://www.w3schools.com/ (tutorials)
- Good information from John Elder at < https://tkinter.com/ >
- realpython.com/python-gui-tkinter
- https://realpython.com/python-virtual-environments-a-primer/
- Site to enter code directly in browser: http://replit.com
- Site with instructions on installing and using opencv: https://www.pyimagesearch.com/
- Site with videos on using python with Excel and Word: https://pythonandvba.com/
- Anvil Works, a site for creating GUI applications with Python: https://anvil.works/ or anvil.works/pythonsimplified
- On line tutorial: https://www.youtube.com/watch?v=NiQdsK3H57Y
- Link to good instructions on how to upgrade Python3 version on Ubuntu https://www.itsupportwale.com/blog/how-to-upgrade-to-python-3-8-on-ubuntu-18-04-lts/
- Data Science Made Simple
Text File Usage
- with open (“filename.txt”, “r,w,or a”) as f:
- text = f.read() or f.readline() or f.readlines()
- you can try putting the above lines in an exception statement to make sure the file opens
- Try:
- with—etc
- except FileNotFound:
- do something here to indicate it
- os.path.
- isfiles(‘_____’) returns true or false
- isdir(‘_____’) returns true or false
- Try:
Simple Copy to Clipboard
- import clipboard
- clipboard.copy(“______”)
- textcopied = clipboard.paste()
Hints on Using Tkinter
- Frame Border
- highlightbackground = “enter color here” (puts a border with your chosen color around the frame)
- highlightthickness = 20 (changes the thickness of the border)
- PhotoImage(file = “____”).subsample(x,y) ==> shrinks photo depending on the numbers you put in x and y, for example 10 and 10
- PhotoImage(file = “____”).zoom(x,y) ==> enlarges photo depending on the numbers you put in x and y
- pack()
- side = LEFT, RIGHT, TOP, BOTTOM
- fill = x, y, BOTH
- padx= , pady= (external)
- ipadx= , ipady= (internal)
- grid()
- row, column
- padx= , pady= (external)
- columnspac
- rowspan
- place()
- x= , y= coordinates
- fill, relx, rely, padx, etc.
- Treeview
- style = ttk.Style()
- style.configure(“Treeview:
- background = “color”,
- foreground = “color”,
- rowheight = 25,
- fieldbackground = “color”)
- style.map(‘Treeview’)
- style.theme_use(“clam or default or alt”)
- Copying information to the main clipboard with Tkinter Where ‘root’ is the main window
- root.clipboard_clear()
- root.clipboard_append()
- root.clipboard_get()
- Bind
- tkinterobject.bind(event, action)
- tkinterobject.bind(“
“, command) - Button-1 (left mouse button) and Button-3 (right mouse button)
- Enter, Leave, Focus
- Return (main enter key)
- KP_Enter (keypad enter key)
- myButton.bind(“<Leave>”, clicker) #On loss of focus#
- myButton.bind(“<FocusIn>”, clicker) #Triggers event on tab into button
- myButton.bind(“<Enter>”, clicker) #Triggers button when hover over it
- myButton.bind(“<FocusOut>”, clicker) #Triggers on loss of focus
- myButton.bind(“<Return>”, clicker) #Left Click
- myButton.bind(“<Key>”, clicker) #Focus on button and hit on a key
- tkinterobject.bind(“<Key>”, command) == put event.keysym in the command to find the name of the key you pressed
- windows to top and background
- window.lower() #puts the tkinter window (root) into the background
- window.lift() #puts the tkinter window (root) into the foreground
- window.attributes(‘-topmost’,True) #keeps window on top at all times
- getting help information on tkinter objects
- my_help = str(help(________)) #where you fill in the blank with the tkinter object, example: Label, Entry, etc.
- print(my_help) #will print the help information on the object to the terminal
Python Modules
- dearpygui
- moviepy
- twillo
- advanced python scheduler
- vpython (for vector 3D graphics)
- openpyxl (for working with Excel files or LibreCalc files with xlsx extensions)
- pandas (installing pandas will automatically install numpy)
- numpy
- xlrd (for reading xlsx files)
- pandas-ods-reader <https://pypi.org/project/pandas-ods-reader/>
- pysimpleGUI
- dataset (python module for connecting to database with simple commands)
- might work for dealing with LibreOffice and LibreCalc odf files
- odfpy, ezodf, pyexcel-ods, py-odftools, simpleodspy, pandas-ods-reader
Link from freecodecamp.org
Python VS JavaScript – what are the key differences? Estefania dives deep into both languages to explore how they handle loops, conditional logic, data types, input/output, and more. (20 minute read): https://www.freecodecamp.org/news/python-vs-javascript-what-are-the-key-differences-between-the-two-popular-programming-languages/
Opencv Hints
Installing Instructions
- pip 3 install opencv-python or python3 -m pip install opencv-python
- may need additional installation of:
- pip3 install scikit-build
- pip3 install cmake
- may need additional installation of:
- for programming use import cv2
Web Scraping Hints
BeautifulSoup
- Real Python Beautiful Soup Reference
- Dataquest Beautiful Soup Tutorial
- Examples of using CSS Selectors
- soup.select(‘p’)
- soup.select(‘p a’) #find the ‘a’ tag within the ‘p’ tag
- soup.select(‘p, a’) #find both the ‘a’ tag and the ‘p’ tag
- soup.select(‘.class’)
- soup.select(‘tag.class’)
- soup.select(‘tag#ID’)
- Use the inspect in browser, go to console tab
- this will allow you to see what information is located in the CSS selector
- $$(‘_________’) where the blank is the CSS Selector to test
MySql Database = possible hints to get it to work on Raspberry Pi
apt install mariadb-client mariadb-common mysql-common libmariadb-dev-compat libmariadbclient-dev
- http://recipes.item.ntnu.no/setting-up-an-sql-database-on-the-raspberry-pi/
- https://betterprogramming.pub/how-to-install-mysql-on-a-raspberry-pi-ad3f69b4a094
- https://www.raspberrypi.org/forums/viewtopic.php?t=272183
- https://mariadb.com/resources/blog/how-to-connect-python-programs-to-mariadb/
SQLite Hints
- Adding a column to an existing table: ALTER TABLE
- addcolumn = “ALTER TABLE _________ ADD COLUMN ________ varchar(32)
- cur.execute(addcolumn)
- where the first blank is the table name and the second blank is the name of the column to add
- ALTER TABLE table name
- ADD COLUMN column ______ definition; (example for blank is “column name text”
- Exporting data from an SQLite database
- Using a program SQLite3
- sudo apt install sqlite3
- SQLite Export using Python
- with open(‘outputfile.csv’, ‘wb’) as f:
- writer = csv.writer(f)
- writer.writerow([‘col1’, ‘col2’, ……])
- writer.writerows(data)
- with open(‘outputfile.csv’, ‘wb’) as f:
- Using a program SQLite3
Virtual Environment for Python
- On macOS and Linux:
- python3 -m pip install –user virtualenv (to install)
- python3 -m venv env (to create in the working directory)
- to start the virtual environment in the working directory, type ‘source env/bin/activate’ (where env is the environment’s name)
- to check if virtual environment is working
- type ‘which python’
- should show that you are using python3 in ‘…/env/bin/python3’
- On Windows:
- py -m pip install –user virtualenv
Creating a virtual environment:
To create a virtual environment, go to your project’s directory and run venv. If you are using Python 2, replace venv with virtualenv in the below commands.
On macOS and Linux:
python3 -m venv env
On Windows:
py -m venv env
The second argument is the location to create the virtual environment. Generally, you can just create this in your project and call it env or virt.
venv will create a virtual Python installation in the env folder.
Note You should exclude your virtual environment directory from your version control system using .gitignore or similar.
Activating a virtual environment
On macOS and Linux:
source env/bin/activate
On Windows:
.\env\Scripts\activate
Leaving the virtual environment
Simply run: deactivate
Clearing / Emptying a List
thelistsname.clear()
Hints for PySimpleGUI
- import PySimpleGUI as sg Link to setting up and basic syntax
- sg.theme(“themename”) Link to sample themes
- sg.theme(‘guess’) #will give you a list of possible themes in the terminal view
- sq.CalendarButton(“cal”)
- http://Trinket.pysimplegui.org
- http://PySimpleGUI.com
- replit.com #website with online IDE
- sg.Column(col_layout)
- sg.Frame(‘title here’, frame_layout)
- sg.TabGroup([sg.Tab(), —>list of tabs])
- possible functions
- popup_get_folder(‘text for popup here’)
- popup_scrolled()
- pad = (L, R) #substitute integers, example (3,6)
- pad = ( (L,R), (T,B) )
- text_color = ‘___ ‘
- background_color =’___ ‘
- enable_events = True
- tooltip = ‘the tip goes here’
- font = (‘Courier 14’)
- use_ttk_buttons = True
- justification = ‘r’ (or center or left)
- target = “key of another element”
- for use with the window, not for the layout
- keep on top
- no_titlebar = True
- grab_anywhere = True
- alpha_channel = .8 #makes the window transparent with levels from 0 to 1
- Creating a function to create a row in a layout
- def DataIn(text, key):
- return[layout row where you replace the text and the key
- BTW, can also do this directly without the replacement variables
- def DataIn(text, key):
- Chooser Buttons
- sg.FileBrowse()
- FilesBrowse
- FolderBrowse
- CalendarButton
- ColorChooserButton
- sg.FileSaveAs
Pip Freeze and Requirements Text File
pip freeze
will produce a similar list of the installed packages, but the output uses the format that pip install
expects. A common convention is to put this list in a requirements.txt
file:
(tutorial-env) $ pip freeze > requirements.txt (tutorial-env) $ cat requirements.txt novas==3.1.1.3 numpy==1.9.2 requests==2.7.0
The requirements.txt
can then be committed to version control and shipped as part of an application. Users can then install all the necessary packages with install -r
:
(tutorial-env) $ python -m pip install -r requirements.txt
You can install multiple python modules manually using: pip install module1 module2 module3 etc
Hints on use of OS Module with Python
- os.mkdir(‘put-new-dir-name-here’)
- os.chdir(‘put-new-working-dir-here’)
- os.getcwd()
- gives you your current working directory
- os.chdir(‘..’)
- moves you Up (back) one directory level
- os.listdir()
- dirlist = os.listdir()
- creates a variable with the names of the directories
- dirlist = os.listdir()
- os.rmdir(‘put-directory-name-here-that-you-want-removed, deleted’)
- os.uname()
- os.remove(‘put-name-of-file-to-remove-here’)
- os.rename(‘old-name’, ‘new-name’)
- open a file
- f = open(‘filename-here’, ‘w’)
- ‘w’ opens the file to write
- ‘r’ opens the file to read
- ‘a’ opens the file to append
- can use a combination as needed, ‘rw’
- f.write(‘line-you-want-in-file’)
- f.read()
- reads the file into memory or a variable
- f.close()
- best to close a file after opening it
- do not need to use this if using ‘f’ in a while statement
- f = open(‘filename-here’, ‘w’)
Hints on Using Lists
- ‘list += another list’ is the same as ‘list = list + another list’
- can be used to create complex layouts with PySimpleGUI
- Adding a list to the end of another list
- list1 = []
- list2 = []
- list1.extend(list2)
- adds list2 to the end of list1
Hints on Using the requests-html library
- item = response.html.xpath(‘ _________ “)
- print(item)
- item = response.html.find(‘ ________ ‘, first=True).text
- if trying to find a class use ‘.nameofclass’ in the blank above
- if trying to find an ID use ‘#nameofID’ in the blank above
Hints on Using the Helium module
- Helium Cheatsheet
- from helium import *
- start_chrome(url=url, headless=False)
- helium.
- go_to(url)
- set_driver(driver path)
- get_driver()
- write(‘text’, into=”____”)
- press(“key”)
- press(ENTER)
- press(CONTROL+”key”)
- click(“element”) doubleclick(“element”)
- click(Button(“OK”))
- click(Point(200,300))
- click(ComboBox(“File Type”).top_left+(50,0))
- find_all()
How to Automatically Install Required Packages From a Python Script?
- https://www.geeksforgeeks.org/how-to-automatically-install-required-packages-from-a-python-script/?ref=rp
- pip3 install pipreqs
- Go to the directory in which your python script is present
- In this directory run the following command that will create a requirement file.
- pipreqs
- pip3 install -r requirements.txt
- https://www.geeksforgeeks.org/12-pip-commands-for-python-developers/?ref=rp
Installing Chromedriver For Selenium
- Make it executable and move to /usr/local/share
- chmod +x ~/Downloads/chromedriver
- sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
- Create symbolic links
- sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
- sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver
- https://bangladroid.wordpress.com/2016/08/10/how-to-install-chrome-driver-in-linux-mint-selenium-webdriver/
- Possible New Chrome Testing Browser for Chromedriver 116
- https://developer.chrome.com/blog/chrome-for-testing/
- https://googlechromelabs.github.io/chrome-for-testing/
- https://stackoverflow.com/questions/76913935/selenium-common-exceptions-sessionnotcreatedexception-this-version-of-chromedri
list comprehension = a way to create a new list with less syntax
- can mimic certain lambda functions, easier to read
- list = [expression for item in iterable]
- list = [expression for item in iterable if conditional]
- list = [expression if/else for item in iterable]
- Example
- students =[100,90,80,70,60,50,40,30,0]
- # passed_students = list (filter ( lambda x: x>=60, students))
- # passed_students =[i for i in students if i>=60]
- passed_students = [i if i >= 60 else “FAILED” for i in students ]
- print (passed_students)
- [100,90,80,70,60, ‘FAILED’, ‘FAILED’, ‘FAILED’, ‘FAILED’ ]
- https://www.youtube.com/watch?v=fcLDzKH_5XM&list=TLPQMTUxMTIwMjNLhhwR0gYtGA&index=3
- Simple code to remember how it works
- new_list = [new_item for item in list]
- new_list = [new_item for item in list if condition]
Dictionary Methods
- values()
- users: dict = {1: ‘Mario’, 2: ‘Ted’, 3: ‘Fred’}
- print(users.values())
- keys()
- print(users.keys())
- pop()
- removes a value related to the key
- users.pop(2)
- popped = users.pop(2)
- print(popped) <this would give the key and value that was removed>
- removes a value related to the key
- popitem()
- copy()
- get()
- setdefault()
- clear()
- fromkeys()
- items()
- update()
Selenium Websites
testautomationpractice.blogspot.com
seleniumhq.org
cosmocode.io
Good link to site with instructions on use of Git and Github
https://guides.github.com/introduction/git-handbook/
Possible way to find and replace an element in a list
a= [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for n, i in enumerate(a):
… if i == 1:
… a[n] = 10
…
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]
Finding and Cleaning Duplicates from a List
testList3 = [2,2,5,3,5,2,28,5,6,7]
duplicates=[i for i in testList3 if testList3.count(i)>1]
unique = set(testList3)
uniqueList = list(unique)
Closing a pop up alert on a web page with selenium video
https://www.youtube.com/watch?v=t90KHbBxVLs&t=1s
driver.switch_to_alert().accept()
driver.switch_to_alert().dismiss()
Simple Auto Scroll Program
https://www.youtube.com/watch?v=ADRSyNKiigM
Using pyautogui
Scrolling a Web Page Using Selenium
https://www.youtube.com/watch?v=aqXkKgkyk2I
Sorting a list within list list
people = [[“Homer”, 2 ,4], [“Marge”, 44 ,45]]
people.sort(key=lambda x: x[2]) #will sort on the 3rd element in each list
people.reverse() #will reverse the above sort order
Placing the driver for selenium to find it on Linux
https://www.youtube.com/watch?v=zjo9yFHoUl8
cd to the folder the driver is in, usually downloads and cp to user/bin
for example for Firefox geckodriver do this ………..
-cd downloads
-sudo cp geckodriver /user/bin/geckodriver
Another Option
There is an easy way to install Geckodriver:
Install webdrivermanager with pip. pip install webdrivermanager.
Install the driver for Firefox and Chrome. webdrivermanager firefox chrome –inkpath /usr/local/bin.
Or install the driver only for Firefox. …
Or install the driver only for Chrome.
Source: https://ostoday.org/linux/how-do-i-run-geckodriver-on-linux.html
Using RoboBrowser
Part 1 of the Series
https://www.youtube.com/watch?v=hrdDIrT9kJI&list=PL5tcWHG-UPH1fnJw-BvBiiiPUPm1LUKsm
Part 2 of the series
https://www.youtube.com/watch?v=Z3vFdtZ7d-g&list=PL5tcWHG-UPH1fnJw-BvBiiiPUPm1LUKsm&index=3
Hitchhiker’s Guide to Python
https://docs.python-guide.org/starting/install3/linux/
tkinter Installation or Setup
For Python 3. sudo apt-get install python3-tk
Installing Pyperclip
sudo apt-get install -y python3-pyperclip
Make it executable and move to /usr/local/share
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
Create symbolic links
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver
https://bangladroid.wordpress.com/2016/08/10/how-to-install-chrome-driver-in-linux-mint-selenium-webdriver/
Installing PyQt5
sudo apt-get install python3-pyqt5
https://pythonbasics.org/install-pyqt/#How-to-install-PyQt5-on-Linux
Instructions on installing and running PyQt5 Designer
https://pythonbasics.org/qt-designer-python/
How to find path to a file, example to Chrome
type the command below to locate chrome in your PC
whereis google-chrome
and execute /usr/bin/google-chrome command to run chrome
import webbrowser
browser_path = “C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s”
url = “https://www.youtube.com”
webbrowser.get(browser_path).open(url)
Great Link for Python Learning and Instructions
https://pythonbasics.org/
Connecting Tkinter Window to Sqlite3 Database
Codemy courses found on Youtube
https://www.youtube.com/watch?v=AK1J8xF4fuk&t=1382s ===== Adding a Record, Video 20
https://www.youtube.com/watch?v=c9_gcIeAru0 ===== Deleting a Record, Video #21
https://www.youtube.com/watch?v=EAs3gr9mC9g ====== Updating a Record, Part 1, Video # 22
https://www.youtube.com/watch?v=0Ms0-68IgTY&t=100s ====== Updating a Record, Part 2, Video # 23
Virtual Environment
To install: pip3 install virtualenv
To use:
— go to the directory where you want to create the python program in the terminal
— use the command: ‘virtualenv .’
— to activate in Linux use: ‘source bin/activate’
— to deactivate use: ‘deactivate’
Add to create a virtual environment in a directory after the virtual environment is installed use:
python3 -m venv XXXXX (where XXXXX is the name of the virtual environment, traditionally ‘virt’)
Tkinter Pack Geometry Manager
https://effbot.org/tkinterbook/pack.htm#patterns
Examples:
pack(fill=BOTH, expand = 1)
pack(fill-X, expand = 1)
pack(fill-Y, expand = 1)
pack(side = LEFT)
note that pady and padx both work with pack
Make a Python File Run in Linux
Making a Python script executable and runnable from anywhere
Add this line as the first line in the script: #!/usr/bin/env python3.
At the unix command prompt, type the following to make myscript.py executable: $ chmod +x myscript.py.
Move myscript.py into your bin directory, and it will be runnable from anywhere.
Now, simply type ./SCRIPTNAME.py to run the executable script
Tkinter Checkbox Use Summary
my-var = IntVar or StringVar
c = Checkbutton(root, text=”whatever”, variable = my_variable) #for interger
c = Checkbutton(root, text=”whatever”, variable = my_variable, onvalue=”something”, offvalue=”something else”) #for string
result = my_var.get()
c.deselect() #when using strings?
Converting Text to Speech with Python
also consider using gTTS which uses Google API to translate the information into a mp3 file
https://www.youtube.com/watch?v=kyZ_5cvrXJI
import pyttsx3
import PyPDF2
book = open(‘oop.pdf’, ‘rb’)
pdfReader = PyPDF2.PdfFileReader(book)
pages = pdfReader.numPages
speaker = pyttsx3.init() #could not get this to work
for num in range(7, pages):
page = pdfReader.getPage(num)
text = page.extractText()
speaker.say(text)
speaker.runAndWait()
Tkinter Text Box Hints
Undo and Redo Options
First Add to the textbox build: undo=True
my_btn = (root, text=”Undo”, command=nameoftextbox.edit_undo)
my_btn = (root, text=”Redo”, command=nameoftextbox.edit_redo)
Using Padding with Widgets
pady = (A, B) # A= padding above, B = padding below example: pady = (20, 10)
padx = (L, R) # L= padding left side, R = padding right side example: padx = (10, 5)
Assigning Focus to an Object
Object.focus() #example Entry.focus()
Tab Order
Depends on the order you create the objects in, packing defines where the object displays on the window
To change tab order check this video: https://www.youtube.com/watch?v=A5Tbh_8nscA
In this video I will show you how to install OpenCV for python in the easiest way within few minutes.
https://www.youtube.com/watch?v=xlmJsTeZL3w&list=TLPQMTcxMTIwMjD3bkyBiCqtkg&index=7
Commands used in this video:
sudo apt-get install libhdf5-dev libhdf5-serial-dev libhdf5-100
sudo apt-get install libqtgui4 libqtwebkit4 libqt4-test
sudo apt-get install libatlas-base-dev
sudo apt-get install libjasper-dev
wget https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py
sudo pip3 install opencv-contrib-python
**Edit : While importing opencv if you get error like “ImportError: /usr/local/lib/python3.7/dist-packages/cv2/cv2.cpython-37m-arm-linux-gnueabihf.so: undefined symbol: __atomic_fetch_add_8” ,then use
“sudo pip3 install opencv-contrib-python==3.4.6.27” – this command as the latest version of openCV doesn’t work with RPi.
https://www.youtube.com/watch?v=WQeoO7MI0Bs
In this video we are going learn everything required to get started with OpenCV in Python. We will be using Python since it is one of the most popular programming languages. And it has opened numerous job opportunities in various sectors. We will start from the installation process right up to creating exciting projects such as detecting colors , shapes humans and even vehicle number plates. So If you are a beginner don’t worry this course is for you. We will skip all the boring theory stuff and focus on the practical implementation. So you can get the computer vision skill set you have always wanted in your CV. By the end of the course you will become familiar with the core principle of opencv and apply different techniques to solve real world problems using computer vision.
Code & Text Based Version: https://www.youtube.com/channel/UCzv_k6lxolY4rzndB71AfUw
Time Stamps: available at the YouTube address of the video
Run Python Script in LibreOffice
https://www.youtube.com/watch?v=3Ef_ordyWQs
https://wiki.openoffice.org/wiki/PyUNO_bridge#PyUNO_bridge_modes
APSO – Alternative Script Organizer for Python-1.0.0
https://extensions.openoffice.org/en/projectrelease/apso-alternative-script-organizer-python-100
How to add background Image in tkinter window and also adding Image in Buttons.
https://www.youtube.com/watch?v=Vejtmbdj9SY&list=TLPQMDMxMjIwMjCXtW_jcnBafg&index=3
Website links:
Background Image: https://www.freepik.com
Text Creating Website: https://textcraft.net
Button Creating Website: http://buttonoptimizer.com
Image Compressor Website: https://www.countingcharacters.com/im…
Tkinter Course:
Part I : https://www.youtube.com/watch?v=ZGf2e…
Part II: https://www.youtube.com/watch?v=IA0zu…
Part III : https://www.youtube.com/watch?v=ZSum_…
Part V : https://youtu.be/LQmFITWZ3BU
Part VI: https://youtu.be/vaDmwpBUQAg
Part VII: https://youtu.be/nJRNkSJUqJE
Part VIII: https://youtu.be/GM5t2J1GUQg
Part IX: https://youtu.be/xwnTimlvDBI
Codemy Book on Django
Link to page and the book pdf
https://codemy.com/django-terminal-commands-ebook
https://codemy.com/books/django-quick-reference-guide.pdf
Information on the use of Python Pillow, PIL, Package from TutorialsPoint
https://www.tutorialspoint.com/python_pillow/python_pillow_quick_guide.htm
==============================
Following example demonstrates the rotation of an image using python pillow −
from PIL import Image
#Open image using Image module
im = Image.open(“images/cuba.jpg”)
#Show actual Image
im.show()
#Show rotated Image
im = im.rotate(45)
im.show()
=============================================
image.filename
image.size
image.format
image.mode
image.save(“name.jpg”)
image.width
image.height
=============================================
from PIL import Image
def tnails():
try:
image = Image.open(‘images/cat.jpg’)
image.thumbnail((90,90))
image.save(‘images/thumbnail.jpg’)
image1 = Image.open(‘images/thumbnail.jpg’)
image1.show()
except IOError:
pass
tnails()
==============================================
The program for resizing and saving the resized image is given below −
#Import required Image library
from PIL import Image
#Create an Image Object from an Image
im = Image.open(“images/cat.jpg”)
#Display actual image
im.show()
#Make the new image half the width and half the height of the original image
resized_im = im.resize((round(im.size[0]*0.5), round(im.size[1]*0.5)))
#Display the resized imaged
resized_im.show()
#Save the cropped image
resized_im.save(‘resizedBeach1.jpg’)
=================================================
First Steps with OpenCV for Python
https://livecodestream.dev/post/first-steps-with-opencv-for-python/
import cv2
img = cv2.imread(“image.jpg”)
scale = 60
width = int(img.shape[1] * scale / 100)
height = int(img.shape[0] * scale / 100)
dim = (width, height)
resized_img = cv2.resize(img, dim, cv2.INTER_AREA)
cv2.imshow(“Resized_Image”, resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()