Why is the value of my Trackbar always -1

Viewed 114

I want to show a movie frame by frame and make some morphological operations on the frame by using Trackbars. Before I create the corresponding structuringselement I need to specify its characteristics such as length, degree and iterations

My code:

import cv2

video = cv2.VideoCapture('arsenal_spurs.mp4')
cv2.namedWindow('Trackbar strel')


def morphology_operations(val):
   length = cv2.getTrackbarPos('length', 'Trackbar strel')
   degrees = cv2.getTrackbarPos('degrees', 'Trackbar strel')
   iter_num = cv2.getTrackbarPos('iterations', 'Trackbar strel')
   print(length, degrees, iter_num)

   return length, degrees, iter_num


cv2.createTrackbar('Length', 'Trackbar strel', 1, 50, morphology_operations)
cv2.createTrackbar('Degrees', 'Trackbar strel', 10, 180, morphology_operations)
cv2.createTrackbar('Iterations', 'Trackbar strel', 1, 10, morphology_operations)


while True:
   ret, frame = video.read()
   if ret:
      morphology_operations(0)
      cv2.imshow('frame', frame)
      # keys to move through the frames
      key = cv2.waitKey(1)
      while key not in [ord('q'), ord('>')]:
         key = cv2.waitKey(0)
      if key == ord('q'):
         break
   else:
     break

video.release()
cv2.destroyAllWindows()

When I run the code I get the Trackbars and frame. However, the values of the three variables are always -1. Also when I drag the Trackbars to different values I get -1 as output.

What am I doing wrong here? Thanks

enter image description here

1 Answers

I rereed docs on the OpenCV - your using of getTrackbarPos is correct. But I also had noticed troubles with OpenCV's Trackbar in the Python. In my previuous projects I had overcame these troubles with the following technics: 1 function per trackbar, this function declared as lambda in the createTrackbar. In your case it can be:

length=0
degrees=0
iter_num=0

def trackbar_length_callback(value):
   global length
   length = value
   print(length)

def trackbar_degrees_callback(value):
   global degrees
   degrees = value
   print(degrees)

cv2.createTrackbar('Length', 'Trackbar strel', 1, 50, lambda a: trackbar_length_callback(a))
cv2.createTrackbar('Degrees', 'Trackbar strel', 10, 180, lambda a: trackbar_degrees_callback(a))

and so on. Probable, it is a suboptimal solution, but you can use it as a start point.

Related