Ask Your Question

Revision history [back]

It looks like you are confused about the last parameter in createTrackbar. You are using it as a result to threshold and in your imshow statement as if it is an image. It is actually a method that's called when the user interacts with the trackbar. In my example, bar() prints the value of the trackbar whenever it is changed. (When you don't need to see that value any more, you can change the body of the method to pass.) I'm using a variable to set the maximum value of the trackbar so that you can easily change the number of thresholding steps. You multiply the trackbar value by 255 / thresholdSteps to get your threshold value. When thresholdSteps is set to 10, you'll get your values of 0 - 255 in steps of 25.5.

import cv2


def bar(x):
    """ Print the value of the trackbar whenever it changes """
    print(f"value: {x}")


img = cv2.imread("pic4.png", cv2.IMREAD_GRAYSCALE)

thresholdSteps = 10
beginningTrackbarValue = 3  # Used in the call to createTrackbar to set the initial trackbar value
cv2.namedWindow("Image")
cv2.createTrackbar("trackbar1", "Image", beginningTrackbarValue, thresholdSteps, bar)

previousTrackbarValue = -1  # Set this to -1 so the threshold will be applied and the image displayed the first time through the loop
while True:
    newTrackBarValue = cv2.getTrackbarPos("trackbar1", "Image")
    # Don't process the image if the trackbar value is still the same
    if newTrackBarValue != previousTrackbarValue:
        thresholdValue = newTrackBarValue * 255 / thresholdSteps
        print(f"threshold value: {thresholdValue}")
        _, threshImg = cv2.threshold(img, thresholdValue, 255, cv2.THRESH_BINARY)
        cv2.imshow("Image", threshImg)
        previousTrackbarValue = newTrackBarValue
    key = cv2.waitKey(10)
    if key == 27:
        break