簡體   English   中英

當我在 function 調用中時,為什么我的全局變量的值沒有改變?

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

所以邏輯很長,但幾乎是幾個軌跡欄改變了某些值,這些值應該分配給捕獲視頻的 while 循環內的某些變量。

這是具有全局定義變量的軌跡欄功能之一:

min_hue = 0
max_hue = 0

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

這是之后的視頻捕獲邏輯

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.

我知道它的更新是因為軌跡欄 function 中的打印語句。 變量變化很好,但如果我在視頻 function 中運行打印語句,則該值永遠不會改變。

該變量在 function 的 scope 之外聲明,因此可以讀取,但不能更新。 如果要更新全局變量,只需在更新 function 中的變量之前添加global min_hue即可訪問它。 喜歡:

min_hue = 0

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM