cv2 getTrackbarPos not working

假装没事ソ 提交于 2019-12-12 03:56:22

问题


Working with opencv3.1 as cv2 in python 2.7.12. The problem I'm having right now is that, though I am following multiple sets of instructions that all seem to use the same setup as myself or at least a very similar one. I am mainly going by these two examples: openCV.org and CodeGenerater's Blogspot tutorial. I did not forget to make a callback function or to use cv2.getTrackbarPos. I feel there must be something wrong with the specific order I do it in or the image display loop. Here is what I have, It diaplays the image with the initial trackbar threshold, but does not update the image with the trackbar callback:

import cv2


#write simple callback function to pass trackbar position as *arg    
def callback(*arg): 
    pass

#create display window for image
cv2.namedWindow('frame') 

#read in image
img = cv2.imread(r'/home/Usr/Documents/Aerial-Images/images_with_targets/Flight_4/target_10.jpg',0)

#instantiate trackbar that goes in our named window and uses callback function
cv2.createTrackbar('thresh2','frame',5,15,callback)

#initialize thresholds
thresh1=11
thresh2=5

#loop really just runs until the escape key causes a break
while(True):

    #sets threshold 2 to trackbar position
    thresh2=cv2.getTrackbarPos('thresh2','frame')   
    #apply laplacian filter to ehance edge gradients
    th = cv2.Laplacian(img,cv2.CV_8UC1)
    #binarize image with adaptive threshold
    th = cv2.adaptiveThreshold(th,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,thresh1,thresh2) 

    #show filtered image
    cv2.imshow('frame',th)
    #waits for escape key then breaks out of loop
    if cv2.waitKey(0) & 0xFF == ord('q'):
        break


#close our display window     
cv2.destroyallwindows()

回答1:


The answer was quite simple really. Upon viewing some older code I wrote, I realized I needed to change the wait key from 0 to 1:

if cv2.waitKey(0) & 0xFF == ord('q'):
    break

became

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

What I did not see was that I forgot to Camel Case cv2.destroyAllWindows, which made me think the display loop was still running when it really was not.




回答2:


#read in image
img = cv2.imread(r'/home/Usr/Documents/Aerial-Images/images_with_targets/Flight_4/target_10.jpg',0)

#instantiate trackbar that goes in our named window and uses callback function
cv2.createTrackbar('thresh2','frame',5,15,callback)

#initialize thresholds
thresh1=11
thresh2=5

This should fall within the while loop



来源:https://stackoverflow.com/questions/39374138/cv2-gettrackbarpos-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!