You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改变量值后无法更新HSV数组?OpenCV实时掩码调整求助

问题解决:OpenCV实时更新HSV掩码阈值

问题根源

你定义的lower和upper阈值数组是在循环外部初始化的,之后即使滑动条修改了全局变量hueL、satL等,这两个数组的值也不会自动同步更新——循环里一直使用的是初始的阈值数组,所以掩码不会随滑动条变化。

修复后的代码

只需把lower和upper的更新逻辑放到循环内部,每次读取帧后重新生成阈值数组即可:

import numpy as np
import cv2 as cv


def change_hueL(value1L):
    global hueL
    hueL = value1L
    print("huel: ", hueL)


def change_satL(value2L):
    global satL
    satL = value2L
    print("satL:", satL)


def change_valL(value3L):
    global valL
    valL = value3L
    print("valL: ", valL)


def change_hueU(value1U):
    global hueU
    hueU = value1U
    print("hueU: ", hueU)


def change_satU(value2U):
    global satU
    satU = value2U
    print("satU: ", satU)


def change_valU(value3U):
    global valU
    valU = value3U
    print("valU: ", valU)


hueL = 50
satL = 50
valL = 150
hueU = 180
satU = 255
valU = 255

cv.namedWindow('panel')
cv.createTrackbar('hue lower', 'panel', hueL, 255, change_hueL)
cv.createTrackbar('sat lower', 'panel', satL, 255, change_satL)
cv.createTrackbar('val lower', 'panel', valL, 255, change_valL)
cv.createTrackbar('hue upper', 'panel', hueU, 255, change_hueU)
cv.createTrackbar('sat upper', 'panel', satU, 255, change_satU)
cv.createTrackbar('val upper', 'panel', valU, 255, change_valU)

cap = cv.VideoCapture(0)

while (True):
    # Capture frame
    ret, frame = cap.read()

    if ret:
        # 每次循环都根据最新的全局变量更新阈值数组
        lower = np.array([hueL, satL, valL])
        upper = np.array([hueU, satU, valU])
        
        color = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        mask = cv.inRange(color, lower, upper)

        cv.imshow("raw", frame)
        cv.imshow("msk", mask)

        k = cv.waitKey(5) & 0xFF
        if k == 27:
            break
cv.destroyAllWindows()
cap.release()

额外优化建议

可以去掉全局变量和回调函数,直接在循环内用cv.getTrackbarPos()获取滑动条当前值,代码更简洁且避免全局变量副作用:

# 移除所有全局变量和回调函数,循环内直接获取值
while (True):
    ret, frame = cap.read()
    if ret:
        hueL = cv.getTrackbarPos('hue lower', 'panel')
        satL = cv.getTrackbarPos('sat lower', 'panel')
        valL = cv.getTrackbarPos('val lower', 'panel')
        hueU = cv.getTrackbarPos('hue upper', 'panel')
        satU = cv.getTrackbarPos('sat upper', 'panel')
        valU = cv.getTrackbarPos('val upper', 'panel')
        
        lower = np.array([hueL, satL, valL])
        upper = np.array([hueU, satU, valU])
        
        # 后续颜色转换、掩码生成、窗口显示逻辑不变

内容的提问来源于stack exchange,提问作者SidTheMadMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:56:02