Ask Your Question
0

Get Trackbar Wont Work

asked 2016-12-27 13:57:07 -0600

updated 2016-12-27 14:03:29 -0600

berak gravatar image

Hi guys, i really need help for my project. Im new to python and openCV. I want to create trackbar for detecting the right threshold values for canny edge detection, However, it seems didnt work. Below is the code:

import numpy as np
import cv2

def nothing(x):
    pass

def find_contour(th1,th2):

    edges = cv2.Canny(gaus,th1,th2)
    contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        color = np.random.randint(0,255,(3)).tolist()
        cv2.drawContours(img,[cnt],0,color,2)
        cv2.imshow('output',img)


img=cv2.imread('C:/Users/USER/Desktop/PytonCVImageProcessing/Tutorials/picture/pineapple.jpg')
grayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gaus=cv2.adaptiveThreshold(grayscaled,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 11, 2) 

cv2.namedWindow('Result',cv2.WINDOW_NORMAL)
cv2.createTrackbar('TH1','Result',0,255,nothing)
cv2.createTrackbar('TH2','Result',0,255,nothing)

find_contour(cv2.getTrackbarPos('TH1','Result'),cv2.getTrackbarPos('TH2','Result'))

while True:
    k = cv2.waitKey(0) & 0xFF     
    if k == 27: break             # ESC key to exit
    cv2.destroyAllWindows()
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2016-12-28 02:45:43 -0600

berak gravatar image

currently, your find_contour function only gets called once, and that, before you can move any trackbars.

let's change the logic a bit, and use the callback function properly:

import numpy as np
import cv2

def find_contour(dummy):
    th1 = cv2.getTrackbarPos('TH1','Result') # get trackbar values
    th2 = cv2.getTrackbarPos('TH2','Result')
    img2 = img.copy() # we need a deep copy here !

    edges = cv2.Canny(gaus,th1,th2)
    contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        color = np.random.randint(0,255,(3)).tolist()
        cv2.drawContours(img2,[cnt],0,color,2)
        cv2.imshow('output',img2)


img=cv2.imread('C:/Users/USER/Desktop/PytonCVImageProcessing/Tutorials/picture/pineapple.jpg')
grayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gaus=cv2.adaptiveThreshold(grayscaled,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 11, 2) 

cv2.namedWindow('Result',cv2.WINDOW_NORMAL)
cv2.createTrackbar('TH1','Result',0,255,find_contour) # new callback !
cv2.createTrackbar('TH2','Result',0,255,find_contour)

find_contour(0) # with a dummy value

cv2.waitKey() # break on ANY key
cv2.destroyAllWindows()
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-12-27 13:57:07 -0600

Seen: 995 times

Last updated: Dec 28 '16