Why doesn't the value of my global variables change when I'm inside a function call?

Question:

So the logic is pretty lengthy but it’s pretty much several trackbars changing certain values which should be assigned to certain variables inside the while loop that captures video.

This is one of the trackbar functions with the variables defined globally:

min_hue = 0
max_hue = 0

def on_min_hue_trackbar(val):
    min_hue = val
    print(f"Change min_hue to {min_hue}" )

And this is the video capture logic that comes after

def videoColorExtraction():
    cap = cv2.VideoCapture(0)
    while True:
        #print(min_hue)
        low_color = np.array([min_hue, min_sat, min_val]).reshape((1,1,3))
        high_color = np.array([max_hue, max_sat, max_val]).reshape((1,1,3))
        ret, frame = cap.read()
        frame = np.flip(frame, 1)
        cv2.imshow('Original', frame)
        cv2.imshow('Extracted', extract color(frame, low_color, high_color))
        if cv2.waitKey(1) == 27:
            break
    cv2.destroyAllWindows()
    cap.release() 

So when I run this function after ive defined the trackbar functions and variables, the initial values of the global "min_hue" variable is assigned in the low_color variable but when its updated in the trackbar function, nothing happens in the video function.

I know its updated because of the print statement in the trackbar function. The variable changes fine but if i run the print statement in the video function, the value never changes.

Asked By: Saif eldeen Adel

||

Answers:

The variable is declared outside of the scope of the function so it can be read, but not updated. If you want to update a global variable, just add global min_hue before updating the variable inside the function to access it. Like:

min_hue = 0

def on_min_hue_trackbar(val):
    global min_hue
    min_hue = val
    print(f"Change min_hue to {min_hue}" )
Answered By: LTJ
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.