OpenCV - 轨迹条滑块在视频中总是回到零

1 投票
1 回答
4903 浏览
提问于 2025-04-18 03:12

我正在尝试使用滑块来控制HSV遮罩的上下限。我可以看到滑块,但每次新的一帧进来时,它的设置位置总是会回到零,无法保持我设定的位置。

import numpy as np
import cv2

def nothing(x):
    pass

cap = cv2.VideoCapture(0)

while(True):

    # Make a window for the video feed  
    cv2.namedWindow('frame',cv2.CV_WINDOW_AUTOSIZE)

    # Capture frame-by-frame
    ret, frame = cap.read()

    # Make the trackbar used for HSV masking    
    cv2.createTrackbar('HSV','frame',0,255,nothing)

    # Name the variable used for mask bounds
    j = cv2.getTrackbarPos('HSV','image')

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

    # define range of color in HSV
    lower = np.array([j-10,100,100])
    upper = np.array([j+10,255,255])

    # Threshold the HSV image to get only selected color
    mask = cv2.inRange(hsv, lower, upper)

    # Bitwise-AND mask the original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    # Display the resulting frame
    cv2.imshow('frame',res)

    # Press q to quit
    if cv2.waitKey(3) & 0xFF == ord('q'):
        break


# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()

1 个回答

2

你在一个循环里不断创建滑块,所以每一帧都会出现一个新的滑块。

所以你可以把代码改成这样:

# Make a window for the video feed  
cv2.namedWindow('frame',cv2.CV_WINDOW_AUTOSIZE)
# Make the trackbar used for HSV masking    
cv2.createTrackbar('HSV','frame',0,255,nothing)

while(True):

    # Capture frame-by-frame
    ret, frame = cap.read()
    ........................
    ........................

撰写回答