Jack
Jack

Reputation: 497

Add trackbar to contour drawing

I am trying to add a trackbar to a script that finds contours to an image in order to show only those contours whose perimeter is longer than the trackbar's value. No matter what I do the contours never change.

Here the code I am using:

import cv2
import numpy as np

# Callback Function for Trackbar (but do not any work)
def nothing(*arg):
    pass

def SimpleTrackbar(Image, WindowName):  
 # Generate trackbar Window Name
 TrackbarName = WindowName + "Trackbar"

 # Make Window and Trackbar
 cv2.namedWindow(WindowName)
 cv2.createTrackbar(TrackbarName, WindowName, 0, 255, nothing)


 im_gray = cv2.cvtColor(Image, cv2.COLOR_RGB2GRAY)
 thresh = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 10)

 #find contours
 _, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST  , cv2.CHAIN_APPROX_SIMPLE)


 # Loop for get trackbar pos and process it
 while True:
  # Get position in trackbar
  TrackbarPos = cv2.getTrackbarPos(TrackbarName, WindowName)
  #draw contours
  cntsfiltered = [cnt for cnt in cnts if cv2.arcLength(cnt, True) > TrackbarPos]
  cv2.drawContours(Image, cntsfiltered, -1, (0, 255, 0), 1)

  # Show in window
  cv2.imshow(WindowName, Image)

  # If you press "ESC", it will return value
  ch = cv2.waitKey(5)
  if ch == 27:
      break

 cv2.destroyAllWindows()
 return Image

imager = cv2.imread("tablebasic.jpg")
SimpleTrackbar(imager, "tre")

Upvotes: 0

Views: 392

Answers (1)

ZdaR
ZdaR

Reputation: 22954

Inside the while True: loop, you are drawing on the same image, you need to maintain a separate copy of original image and project contours on this copy, keeping the original image as it is. It can be done as:

while True:
 # Get position in trackbar
 TrackbarPos = cv2.getTrackbarPos(TrackbarName, WindowName)
 # draw contours
 img_copy = Image.copy()
 cntsfiltered = [cnt for cnt in cnts if cv2.arcLength(cnt, True) > TrackbarPos]
 cv2.drawContours(img_copy, cntsfiltered, -1, (0, 255, 0), 1)

 # Show in window
 cv2.imshow(WindowName, img_copy)

 # If you press "ESC", it will return value
 ch = cv2.waitKey(5)
 if ch == 27:
     break

cv2.destroyAllWindows()
return img_copy 

Upvotes: 1

Related Questions