'UnboundLocalError: local variable 'input_img' referenced before assignment Tkinter

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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source