我一直在运行OpenCV文档中的轨迹栏程序。
这是代码:

 import cv2
 import numpy as np

 def nothing(x):
    pass

 # Create a black image, a window
 img = np.zeros((300,512,3), np.uint8)
 cv2.namedWindow('image')

 # create trackbars for color change
 cv2.createTrackbar('R','image',5,255,nothing)
 cv2.createTrackbar('G','image',5,255,nothing)
 cv2.createTrackbar('B','image',5,255,nothing)

 # create switch for ON/OFF functionality
 switch = '0 : OFF \n1 : ON'
 cv2.createTrackbar(switch, 'image',0,1,nothing)

 while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
       break

    # get current positions of four trackbars
    r = cv2.getTrackbarPos('R','image')
    **if r%4 == 0 and r >0 and r <255:
       pass**
    g = cv2.getTrackbarPos('G','image')
    b = cv2.getTrackbarPos('B','image')
    s = cv2.getTrackbarPos(switch,'image')

    if s == 0:
      img[:] = 0
    else:
      img[:] = [b,g,r]

    cv2.destroyAllWindows()

我希望轨迹栏步长为4,即,范围设置为0-255,我希望值可以被4整除。我已经在nothing回调中调整了以下内容:
def nothing(x):
    if x > 0 and x <255 and x % 4 ==0
       pass

另外我还添加了一个代码(粗体),但这也不起作用
任何人有解决方案吗?

最佳答案

尽管OpenCV中没有参数来指定步长,但是您可以修改算法以合并步长:

当前,您有一个可以从1-255移动的跟踪栏。您正在按原样阅读其位置,但是您只对值{4,8,12,16 ...}感兴趣

您可以将轨迹栏的范围从[1-255]减少为[1-63],作为int(255/4)=63
然后,当您收到轨迹栏位置时,可以将其乘以4,这样您的轨迹栏范围将如下所示:

{1,2,3,4 ... 63} x 4 = {4,8,12,16 ... 252}

您可以按照如下所示的代码进行操作:

cv2.createTrackbar('R','image',1,63,nothing)
#create trackbar with reduced range
...

 r = cv2.getTrackbarPos('R','image')
 r=4*r
 #read reduced range and scale it up

关于python - 使cv2.createTrackbar指定步长并丢弃某些值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40612662/

10-11 21:28