Introduction
In the previous post, we discussed how to rotate an image using python. We used two python libraries, OpenCV, and Pillow to perform the task. In this tutorial, we'll create an Image Rotator Application using Python. We'll make this project GUI by using the python Tkinter library so that it would be easy to use by every user.
So, before going to proceed, please know how the image rotator does work.
☛Visit Also: Create an Image Viewer Application using Python
How the Image Rotator does Work?
Since it's a GUI project(using Tkinter), we've to open an image through the Tkinter file dialog. When the image is selected from a directory, a function is called for showing that image in the middle of the main Tkinter window. On the main window, there are two buttons, 'Left' and 'Right' on the left and right sides of the image respectively.
Once a button('Left' or 'Right') is pressed, the selected image(that is showing on the screen) will rotate 90 degree ClockWise(for 'Right' button) or Anti-ClockWise(for 'Left' button) as well as display the rotated image on the screen in the same position, and will automatically rewrite that rotated image with the main image in the same location where the image is located.
What can you learn from this project?
- Creating a graphical interface with Tkinter: Creating Tkinter window, frame, label, buttons, etc.
- Displaying an image on Tkinter Window using another function(out of the main function)
- How to rotate an image using python
- Object-Oriented Programming: Use of Class, object, etc.
Requirements
☛Install Tkinter: pip install tk
☛Install OpenCV: pip install opencv-python
☛Install Pillow: pip install Pillow
Import the Modules
Let's create a Python file with the name "ImageRotator.py" and start writing the code by importing these modules.
import os
import cv2
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
Declare Image Rotator Class
Declare a class called "Image_Rotator" that will create a GUI window for us and manage all the tasks related to the Image Rotating.
class Image_Rotator:
def __init__(self, root):
self.window = root
self.window.geometry("960x600")
self.window.title('Image Rotator')
self.window.resizable(width = False, height = False)
# Declare some variables that
# initially store None value
self.img = img
self.rot_image = rot_image
self.image_name = image_name
self.Image_Path = image_path
self.width = 740
self.height = 480
# ==============================================
# ================Menubar Section===============
# ==============================================
# Creating Menubar
self.menubar = Menu(self.window)
# Adding Edit Menu and its sub menus
edit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Open', menu=edit)
edit.add_command(label='Open Image',command=self.Open_Image)
# Exit the Application
exit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Exit', menu=exit)
exit.add_command(label='Exit', command=self.Exit)
# Configuring the menubar
self.window.config(menu=self.menubar)
# ===================End=======================
left_btn = Button(self.window, text="Left", \
font=("Helvetica", 15, 'bold'), command=self.Rotate_Left)
left_btn.place(x=15,y=270)
right_btn = Button(self.window, text="Right", \
font=("Helvetica", 15, 'bold'), command=self.Rotate_Right)
right_btn.place(x=865,y=270)
# Creating a Frame
self.frame_1 = Frame(self.window, \
width=self.width,height=self.height)
self.frame_1.pack()
self.frame_1.place(anchor='center', relx=0.5, rely=0.5)
Declare a Function to Open an Image
Let's declare a function for opening an image through the tkinter file dialog. Users can select '.jpg', '.jpeg', '.png' type of images only.
# Onen an Image
def Open_Image(self):
self.Clear_Screen()
self.Image_Path = \
filedialog.askopenfilename(initialdir = "/", \
title = "Select an Image", \
filetypes = (("Image files", "*.jpg *.jpeg *.png"),))
if len(self.Image_Path) != 0:
self.image_name = os.path.basename(self.Image_Path)
if self.image_name != '':
self.Show_Image()
Declare a Function to Show an Image
Now declare another function to show the selected image on the Tkinter window. It's quite a tricky task to show an image from the out of the main function because, python garbage collector removes the memory occupied by the variables when they are no longer in use(it generally happens when we leave a function, the variables declares in there are released by the garbage collector).
So, I've declared those variables in the main function earlier and the instances of those in the Image_Rotator class for avoiding the image vanishing from the Tkinter window.
# Show the selected Image
def Show_Image(self):
image = Image.open(self.Image_Path)
resized_image = image.resize((self.width, self.height))
# Create an object of tkinter ImageTk
self.img = ImageTk.PhotoImage(resized_image)
# Create a Label Widget to display the Image
label = Label(self.frame_1, image=self.img)
label.pack()
Rotate the Image ClockWise and Save
Now declare a function for rotating the selected image 90 degree ClockWise and save that using the cv2.imwrite() function. I've used the OpenCV library here to perform this task.
# When the 'Right' button is pressed
# this function gets a call
def Rotate_Right(self):
if self.image_name == None:
pass
else:
data = cv2.imread(self.Image_Path)
self.rot_image = cv2.rotate(data, cv2.cv2.ROTATE_90_CLOCKWISE)
cv2.imwrite(self.Image_Path, self.rot_image)
self.Clear_Screen()
self.Show_Image()
Rotate the Image Anti-ClockWise and Save
Almost the same as the above but the image will rotate Counter ClockWise here.
# When the 'Left' button is pressed
# this function gets a call
def Rotate_Left(self):
if self.image_name == None:
pass
else:
data = cv2.imread(self.Image_Path)
self.rot_image = cv2.rotate(data, \
cv2.cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imwrite(self.Image_Path, self.rot_image)
self.Clear_Screen()
self.Show_Image()
Clear the Screen
This function will remove all the widgets(only the image) from the 'frame_1'.
# Remove all widgets from the frame_1
def Clear_Screen(self):
for widget in self.frame_1.winfo_children():
widget.destroy()
Exit Function
Declare a function to exit the main window.
# It destroys the main GUI window of the
# application
def Exit(self):
self.window.destroy()
The main Function
# The main function
if __name__ == "__main__":
root = Tk()
# Creating these objects for avoiding
# image vanishing(Garbage Collector)
img = None
rot_image = None
image_name = None
image_path = None
# Creating a Image_Rotator class object
obj = Image_Rotator(root)
root.mainloop()
Full Code
'''Image Rotator using Python
Copyright (c) 2022 Subhankar Rakshit
~PySeek~'''
import os
import cv2
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
class Image_Rotator:
def __init__(self, root):
self.window = root
self.window.geometry("960x600")
self.window.title('Image Rotator')
self.window.resizable(width = False, height = False)
# Declare some variables that
# initially store None value
self.img = img
self.rot_image = rot_image
self.image_name = image_name
self.Image_Path = image_path
self.width = 740
self.height = 480
# ==============================================
# ================Menubar Section===============
# ==============================================
# Creating Menubar
self.menubar = Menu(self.window)
# Adding Edit Menu and its sub menus
edit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Open', menu=edit)
edit.add_command(label='Open Image',command=self.Open_Image)
# Exit the Application
exit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Exit', menu=exit)
exit.add_command(label='Exit', command=self.Exit)
# Configuring the menubar
self.window.config(menu=self.menubar)
# ===================End=======================
left_btn = Button(self.window, text="Left", \
font=("Helvetica", 15, 'bold'), command=self.Rotate_Left)
left_btn.place(x=15,y=270)
right_btn = Button(self.window, text="Right", \
font=("Helvetica", 15, 'bold'), command=self.Rotate_Right)
right_btn.place(x=865,y=270)
# Creating a Frame
self.frame_1 = Frame(self.window, \
width=self.width,height=self.height)
self.frame_1.pack()
self.frame_1.place(anchor='center', relx=0.5, rely=0.5)
# Onen an Image
def Open_Image(self):
self.Clear_Screen()
self.Image_Path = \
filedialog.askopenfilename(initialdir = "/", \
title = "Select an Image", \
filetypes = (("Image files", "*.jpg *.jpeg *.png"),))
if len(self.Image_Path) != 0:
self.image_name = os.path.basename(self.Image_Path)
if self.image_name != '':
self.Show_Image()
# Show the selected Image
def Show_Image(self):
image = Image.open(self.Image_Path)
resized_image = image.resize((self.width, self.height))
# Create an object of tkinter ImageTk
self.img = ImageTk.PhotoImage(resized_image)
# Create a Label Widget to display the text or Image
label = Label(self.frame_1, image=self.img)
label.pack()
# When the 'Right' button is pressed
# this function gets a call
def Rotate_Right(self):
if self.image_name == None:
pass
else:
data = cv2.imread(self.Image_Path)
self.rot_image = cv2.rotate(data, cv2.cv2.ROTATE_90_CLOCKWISE)
cv2.imwrite(self.Image_Path, self.rot_image)
self.Clear_Screen()
self.Show_Image()
# When the 'Left' button is pressed
# this function gets a call
def Rotate_Left(self):
if self.image_name == None:
pass
else:
data = cv2.imread(self.Image_Path)
self.rot_image = cv2.rotate(data, \
cv2.cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imwrite(self.Image_Path, self.rot_image)
self.Clear_Screen()
self.Show_Image()
# Remove all widgets from the frame_1
def Clear_Screen(self):
for widget in self.frame_1.winfo_children():
widget.destroy()
# It destroys the main GUI window of the
# application
def Exit(self):
self.window.destroy()
# The main function
if __name__ == "__main__":
root = Tk()
# Creating these objects for avoiding
# image vanishing(Garbage Collector)
img = None
rot_image = None
image_name = None
image_path = None
# Creating a Image_Rotator class object
obj = Image_Rotator(root)
root.mainloop()
Conclusion
In this tutorial, we build an Image Rotator Application using Python. You can rotate any image 90 degree left or right using it.After performing the rotation operation, the rotated image is saved in the place of the original one. Rotate an image using this lovely application and let me know in the comment section, it's working fine or not.
You can ask me any questions related to this topic too. I will get back to you, with the answer soon.
Thanks for reading!💙
PySeek