Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd numbers only on OpenCV trackbar for Python?

Tags:

python

opencv

I am learning how to use OpenCV on Python for skin segmentation and right now I am mostly in the experimental phase, where I am playing with the Gaussian Blue to reduce the sharp contrasts which I am getting with Otsu's Binarization.

One stratergy that I found very useful in my experimentation was to use the trackbar functionality on the display window to change various parameters such as selection of the kernel size and standard deviation of the Gaussian function. The trackbar works great when I change the std, but my program crashes when I do the same for kernel size.

The reason for this is that kernel size takes only odd numbers > 1 as a tuple of two values. Since the track bar is continuous, when I move it and the trackbar reads an even number, the Gaussian function throws an error.

I was hoping that you could provide me with a solution to create a trackbar with only odd numbers or even only numbers from an array, if possible. Thanks!

# applying otsu binerization to video stream
feed = cv2.VideoCapture(0)

# create trackbars to control the amount of blur 
cv2.namedWindow('blur')
# callback function for trackbar
def blur_callback(trackbarPos):
    pass
# create the trackbar 
cv2.createTrackbar('Blur Value', 'blur', 1, 300, blur_callback)
# cv2.createTrackbar('Kernel Size', 'blur', 3, 51, blur_callback)

while True:
    vid_ret, frame = feed.read()
    # flip the frames 
    frame = cv2.flip(frame, flipCode=1)

    # convert the feed to grayscale
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # get blur value from trackbar and apply gaussian blur to frame_gray
    blurVal = cv2.getTrackbarPos('Blur Value', 'blur')
#     kernelSize = cv2.getTrackbarPos('Kernel Size', 'blur')
    frame_blur = cv2.GaussianBlur(frame_gray, (11, 11), blurVal)

    # apply Otsu binerization on vanilla grayscale
    otsu_ret, otsu = cv2.threshold(frame_gray, 0, 255, cv2.THRESH_OTSU)

    # apply Otsu binerization on blurred grayscale
    otsu_blue_ret, otsu_blur = cv2.threshold(frame_blur, 0, 255, cv2.THRESH_OTSU)


    # show the differnt images
    cv2.imshow('color', frame)
#     cv2.imshow('gray', frame_gray)
    cv2.imshow('blur', frame_blur)
    cv2.imshow('otsu', otsu)
    cv2.imshow('otsu_blur', otsu_blur)
    # exit key
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

# release the feed and close all windows
feed.release()
cv2.destroyAllWindows()
like image 959
Vignesh Viswanathan Avatar asked Apr 27 '26 18:04

Vignesh Viswanathan


1 Answers

To add to Louis' answer, you can move the trackbar to the odd position by using setTrackbarPos()

see: https://docs.opencv.org/trunk/d7/dfc/group__highgui.html#ga67d73c4c9430f13481fd58410d01bd8d

like image 188
Arnþór Gíslason Avatar answered Apr 30 '26 08:04

Arnþór Gíslason