Python OpenCV Trackbar Error For cv2.getTrackbarPos

2.1k views Asked by At

I'm attempting to execute the following Python 3.9.5 script using Visual Studio Code on a Windows 10 PC:


import cv2
import numpy as np

frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(1)
cap.set(3, frameWidth)
cap.set(4, frameHeight)


def empty(a):
    pass

cv2.namedWindow("HSV")
cv2.resizeWindow("HSV", 640, 240)
cv2.createTrackbar("HUE MIN", "HSV", 0, 179, empty)
cv2.createTrackbar("HUE Max", "HSV", 129, 129, empty)
cv2.createTrackbar("SAT Min", "HSV", 0, 255, empty)
cv2.createTrackbar("SAT Max", "HSV", 255, 255 ,empty)
cv2.createTrackbar("VALUE Min", "HSV", 0, 255, empty)
cv2.createTrackbar("VALUE Max", "HSV", 255, 255, empty)

cap = cv2.VideoCapture('vid1.mp4')
frameCounter = 0

while True:
    frameCounter +=1
    if cap.get(cv2.CAP_PROP_FRAME_COUNT) == frameCounter:
        cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
        frameCounter=0

    _, img = cap.read()
    imgHsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    h_min = cv2.getTrackbarPos("HUE Min", "HSV")
    h_max = cv2.getTrackbarPos("HUE Max", "HSV")
    s_min = cv2.getTrackbarPos("SAT Min", "HSV")
    s_max = cv2.getTrackbarPos("SAT Max", "HSV")
    v_min = cv2.getTrackbarPos("VALUE Max", "HSV")
    v_max = cv2.getTrackbarPos("VALUE Max", "HSV")
    print(h_min)

    lower = np.array([h_min, s_min, v_min])
    upper = np.array([h_max, s_max, v_max])
    mask = cv2.inRange(imgHsv, lower, upper)
    result = cv2.bitwise_and(img, img, mask=mask)

    mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    hstack = np.hstack([img, mask, result])
    cv2.imshow('Horizontal Stacking', hstack)
    if cv2.waitKey(1) and 0xFF == ord('q'):
        cv2.waitKey(0)

cap.release()
cv2.destroyAllWindows()

However, upon execution, I get the following error:

[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (539) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Traceback (most recent call last):
  File "c:...\ColorPickerScript.py", line 35, in <module>
    h_min = cv2.getTrackbarPos("HUE Min", "HSV")
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:862: error: (-215:Assertion failed) trackbar in function 'cv::getTrackbarPos'

I was hoping someone could point me in the correct direction to figure out why this is happening and what I can do to fix it. I haven't been able to find any solutions yet, thanks!

1

There are 1 answers

2
Voltage_Cat On

As pointed out by Christoph Rackwitz, the problem was that I made a type, where I had one string in all caps but not the other. Correcting this fixed the issue.