I tried to detect blue color from entry input image using both Tkinter and OpenCV where when 'Display Image 2' button is pressed second window will display and I was expecting the image where blue color from image is detected to displays on the second window but turned out it doesn't. Why?
Output Error: UnboundLocalError: local variable 'input_img' referenced before assignmentTkinter
from tkinter import *
from PIL import ImageTk, Image
import tkinter as tk
import cv2
import numpy as np
window = Tk()
window.title("Color detector")
window.geometry("800x500")
input_img = tk.Entry(window)
input_img.pack()
def detect_color():
new_wind = Toplevel()
new_wind.title('Ur mom')
# Get Image
input_img = str(input_img.get())
global img
path = r'C:\\users\\HP\\Documents\\' + input_img
img = ImageTk.PhotoImage(Image.open(path))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([[90,50,50]])
upper_blue = np.array([[130,255,255]])
mask = cv2.inRange(hsv,lower_blue,upper_blue)
result = cv2.bitwise_and(img,img,mask=mask)
display_result = Label(new_wind,image=result)
display_result.pack()
display_img = tk.Button(window, text='Display Image 2',command=detect_color)
display_img.pack()
window.mainloop()
So this is the image I use in this case:
The output:
Output I expected:
Related
from tkinter import *
from PIL import Image, ImageTk, ImageSequence
import time
def play_gif():
global img
img = Image.open("document2.gif")
lbl = Label(root)
lbl.place(x=150,y=50)
for img in ImageSequence.Iterator(img):
img = img.resize((300,300))
img = ImageTk.PhotoImage(img)
lbl.config(image = img)
root.update()
time.sleep(0.04)
root.after(0,play_gif)
root = Tk()
root.geometry("600x400")
#root.configure(bg="white")
play_gif()
root.mainloop()
When I close the tkinter window, I am getting the above error, can somebody please help me fix it ?
I want to run gif in ttkinter window as a loading screen
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
This is my code for the button that opens an app:
Modules:
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from subprocess import Popen
Importing Image:
path = ("C:\Pictures\GoogleLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
Generic Canvas Button:
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey", height = 6, width = 10)
canvas.create_window(1167,714, window=openCalcWin)
What I have Tried:
I attempted to make the background of the button into an image by using bg or img. But this just creates an tiny image logo that can't be clicked. Indicating that there was an error loading the image, but there was no error code or anything in the IDLE Shell.
There was other attempts of code that I forgot, but most of them ends up the same: no button appeared and no error code.
Edit:
import tkinter as tk
from PIL import ImageTk, Image
from subprocess import Popen
##Application Window:
root=tk.Tk()
root.title("Virtual Desktop")
root.resizable(False, False)
#Determine Window Resolution
canvas = tk.Canvas(root, width=1280, height=780, bg="#263D42")
canvas.pack()
#Importing Calulator Image
path = ("C:\Pictures\CalcLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
#Calculator Button
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey", height = 6, width = 10)
canvas.create_window(1167,714, window=openCalcWin)
The following works for me. The most important change was to specify an image= keyword argument, when creating the Button.
The other thing I noted was the:
path = ("C:\Pictures\CalcLogo.png")
you had. The parentheses are unnecessary (but don't hurt), however you need to add an r prefix to all strings containing back-slash characters like paths on Windows.
path = r"C:\Pictures\CalcLogo.png"
or just use forward-slashes (which work fine on Windows):
path = "C:/Pictures/CalcLogo.png"
Full code:
import tkinter as tk
from PIL import ImageTk, Image
from subprocess import Popen
##Application Window:
root=tk.Tk()
root.title("Virtual Desktop")
root.resizable(False, False)
#Determine Window Resolution
canvas = tk.Canvas(root, width=1280, height=780, bg="#263D42")
canvas.pack()
#Importing Calulator Image
path = "8-ball.png" # My own image.
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
#Calculator Button
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey",
image=img)
canvas.create_window(1167,714, window=openCalcWin)
root.mainloop()
I found this solution. You can check it learn about it yourself, but basically you do not provide any args when creating the obj/Button, you only provide the root, image and command, and it should work.
Something like this:
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from subprocess import Popen
root = Tk()
path = ("C:\Pictures\GoogleLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', image=img, command=openCalc)
openCalcWin.pack()
root.mainloop()
if you want, you can look at some examples and learn more here - https://www.activestate.com/resources/quick-reads/how-to-add-images-in-tkinter/
from PIL import Image, ImageTk
import numpy as np
import tkinter as tk
import time
def put_pixel(row, col):
pixels[row, col] = [255, 255, 255]
width = 20
height = 10
pixels = np.full((height, width, 3), 0, dtype=np.uint8)
root = tk.Tk()
root.geometry("300x300")
root.configure(background='grey')
img = ImageTk.PhotoImage(Image.open("maze.png"))
panel = tk.Label(root, image=img)
panel.pack(side = "top")
b = tk.Button(root, text="Sure!")
b.pack(side="bottom", fill="both")
for i in range(1, width-2, 2):
put_pixel(5, i)
time.sleep(2)
img = Image.fromarray(pixels, 'RGB')
panel.configure(image=img)
panel.image = img
root.mainloop()
The script just adds white pixels on a black image. But I want it to be animated to see the adding of every pixel step by step. So I tried to update an image in a label after every single pixel being added. But I got an error
_tkinter.TclError: image "" doesn't exist
If I don't use loop and just put an image into a label it works fine. How do I fix that?
You need to convert the PIL.Image into a tkinter.PhotoImage:
img = Image.fromarray(pixels, 'RGB')
tkimg = ImageTk.PhotoImage(img)
panel.configure(image=tkimg)
panel.image = img
tkinter.Label will only accept this type, not PIL images.
I'm using tkinter and I have a "sprite sheet" and I want to cut it into multiple images. I tried PIL:
img = Image.open("test.png").convert("RGBA")
img2 = img.crop([300,300,350,350])
image = ImageTk.PhotoImage(img2)
win = tk.Tk()
label = tk.Label(win, image = image)
label.pack()
but on my window, there is only an empty white rectangle and I don't understand why. Moreover I tried img2.show() just to make shure that img2 wasn't empty and it wasn't.
Here is your code, with a few changes. Note the call to Tk() at the top, and mainloop() at the bottom. The other modification is that it obtains the width and height of the image and then crops 25% from each of the four sides to leave the middle 50% of the image.
#!/usr/bin/python
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
img = Image.open("test.png").convert("RGBA")
w, h = img.size
left = w/4
right = 3*w/4
upper = h/4
lower = 3*h/4
img2 = img.crop([ left, upper, right, lower])
image = ImageTk.PhotoImage(img2)
label = Label(root, image = image)
label.pack()
root.mainloop()