Oct-24-2022, 06:20 PM
A program that reads and writes image files using opencv and displays them in tkinter.
import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk import cv2 class Application(tk.Tk): def __init__(self, image_path=None): super().__init__() self.title("Image Processing") self.geometry("400x300") self.image = None # Image used for image processing self.tkimage = None # Image used to display in tkinter label self.display = tk.Label(self) self.display.pack(expand=True, fill=tk.BOTH) # Make a frame to pack the buttons horizontally buttons = tk.Frame(self) buttons.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=5) # Make buttons to load image, save image and quit button = tk.Button(buttons, text="LOAD IMAGE", command=self.load_image) button.pack(side=tk.LEFT, expand=True, fill=tk.X) button = tk.Button(buttons, text="SAVE FILE", command=self.save_image) button.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5) button = tk.Button(buttons, text="CLOSE", command=self.destroy) button.pack(side=tk.LEFT, expand=True, fill=tk.X) def load_image(self): """Select an image to display""" filename = filedialog.askopenfilename() if filename: # Read image and convert to RGB self.image = cv2.imread(filename) self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB) # Convert image to tkinter image format and display self.tkimage = ImageTk.PhotoImage(Image.fromarray(self.image)) self.display["image"] = self.tkimage def save_image(self): """Save image to a file""" filename = filedialog.asksaveasfilename(defaultextension='.jpg') if filename: # Convert image to BGR and write to file. cv2.imwrite(filename, cv2.cvtColor(self.image, cv2.COLOR_RGB2BGR)) Application().mainloop()