为什么这个Python Open CV程序中的跟踪栏不显示?

时间:2014-11-09 03:46:05

标签: python opencv

我目前正在学习如何使用Open CV for python,我正在尝试编写一个程序,以基于hsv值范围从网络摄像头实时查看图像。当我运行该程序时,我能够使网络摄像头工作(它显示了预期的黑屏),但调整hsv范围的轨迹栏由于某种原因没有显示。有人有任何解决方案?感谢。

import cv2
import numpy as np
cap = cv2.VideoCapture(0)

def nothing(x):
    pass


#creates three trackbars for color change
cv2.createTrackbar('H','frame',0,255,nothing)
cv2.createTrackbar('S','frame',0,255,nothing)
cv2.createTrackbar('V','frame',0,255,nothing)

while(1):
    # Capture frame-by-frame
    _, frame = cap.read()

    #creates trackbars
    h = cv2.getTrackbarPos('H','frame')
    s = cv2.getTrackbarPos('S','frame')
    v = cv2.getTrackbarPos('V','frame')


    # Converts from BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define color strenght parameters in HSV
    weaker = np.array([h+10, s+10, v+10])
    stronger = np.array([h-10,s-10,v-10])


    # Threshold the HSV image to obtain input color
    mask = cv2.inRange(hsv, weaker, stronger)

    #displays mask
    cv2.imshow('Result',mask)

    #terminates program
    if cv2.waitKey(1) == ord('q'):
        break

cv2.waitKey(0)
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:1)

cv2.createTrackbar('H','frame',0,255,nothing)的第二个参数应该是显示轨迹栏的窗口的名称。您已使用frame,但似乎没有在您的代码中打开名为frame的窗口。你可以通过添加

来实现
cv2.namedWindow('frame')

或将显示行更改为

cv2.imshow('frame', mask)