简体   繁体   中英

How to display the image after clicking the button?

I am trying to make an application that applies filters to an image but it shows an exception after reading image_label_filtered=Label(image=filtered_image) saying _tkinter.TclError: image doesn't exist.

from tkinter import *
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import ImageTk,Image

root=Tk()
root.title("image processing")
original_image=ImageTk.PhotoImage(Image.open("E:/college materials/third year first term/image processing/section/noised_image.png"))
original_image_for_filter=cv2.imread("E:/college materials/third year first term/image processing/section/noised_image.png")

image_label=Label(image=original_image)
image_label.grid(row=0,column=0)

def button_Blur(): 
    filtered_image=cv2.blur(original_image_for_filter,(5,5))
    image_label_filtered=Label(image=filtered_image)
    image_label_filtered.grid(row =0, column=1) 

button_blur=Button(root,text="apply blur filter",command=button_Blur)
button_blur.grid(row=1,column=0)
root.mainloop()

You need to convert the image to tkinter.PhotoImage compatible format, like ImageTk.PhotoImage in order to be used as the image of a Label widget:

def button_Blur():
    image = cv2.blur(original_image_for_filter, (5,5))
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # BGR to RGB
    image = Image.fromarray(image) # convert to Image format
    filtered_image = ImageTk.PhotoImage(image) # convert to PhotoImage format
    image_label_filtered = Label(image=filtered_image)
    image_label_filtered.grid(row =0, column=1)
    # keep a reference of the image to avoid garbage collected
    image_label_filtered.image = filtered_image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM