0

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:

enter image description here

The output:

enter image description here

Output I expected:

enter image description here

  • 2
    If a variable is assigned a value inside a function, the variable will be treated as local variable if it is not declared as global using `global ...`. So the line `input_img = str(input_img.get())` will try to look up a local variable `input_img` but failed. – acw1668 Mar 18 '22 at 05:45
  • Thanks. But how do I imply your explanation to my code? –  Mar 18 '22 at 05:51
  • Use another variable name for the left hand side of the line `input_img = str(input_img.get())`. – acw1668 Mar 18 '22 at 05:56
  • Thanks.. but the same problem still occurrs –  Mar 18 '22 at 06:02
  • "cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'cvtColor' > Overload resolution failed: > - src is not a numpy array, neither a scalar > - Expected Ptr for argument 'src'" Displays on my console –  Mar 18 '22 at 06:04
  • It is *another issue* because you apply `OpenCV` function on a `Pillow` image. – acw1668 Mar 18 '22 at 06:05
  • Ok thanks I will find way to solve it. –  Mar 18 '22 at 06:06
  • Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – Ulrich Eckhardt Mar 18 '22 at 07:38
  • Just in general, first search for the error message online if you don't understand it. Then, extract a [mcve]. If both doesn't help, ask a question here. – Ulrich Eckhardt Mar 18 '22 at 07:39

0 Answers0