Python - Filter contour by shape (find circles after HSV filtering)

asked 2018-10-31 01:36:50 -0600

Ops gravatar image

Hi, I'm working on a project and I'm trying to follow the position of tennis table ball with OpenCV on python using webcam. To track it, I start by applying a Gaussian blurr filter and then convert it to HSV space . Now i'm facing a problem, my conversion to the HSV space doesn't delete blops from my hand for example.

So my next step is filter my contours by shape in order to find circle only and then compute its center and radius by minenclosing function.

But i have no idea how to proceed, i check houghcircles but it works only for a 8 bits channel. I also checked edge detection but it decrease strongly my accuracy.

Any help is welcomed ! Thank you. (Inspired from : https://www.pyimagesearch.com/2015/09...)

My code below :

from collections import deque
import numpy as np
import argparse
import cv2
import imutils
import time

ap = argparse.ArgumentParser()
ap.add_argument("-b", "--buffer", type=int, default=128,
help="max buffer size")
args = vars(ap.parse_args())

color_tracked_lower = (9, 59, 144)
color_tracked_upper = (22, 150, 255)
pts = deque(maxlen=args["buffer"])

webcam = cv2.VideoCapture(0) 
webcam.set(3,320)
webcam.set(4,240)
num_frames=120 
webcam.set(cv2.CAP_PROP_FPS, num_frames)

while(True):
    _,frame = webcam.read()
    blurred = cv2.GaussianBlur(frame, (11, 11), 0) 
    hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) #Conversion en HSV
    mask = cv2.inRange(hsv, color_tracked_lower, color_tracked_upper) #Construction du mask
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, None)

         cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[1]
     center = None
     if len(cnts) > 0:
         c = max(cnts, key=cv2.contourArea)
         ((x, y), radius) = cv2.minEnclosingCircle(c)
         M = cv2.moments(c)
         center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
         if radius>5:
             cv2.circle(frame, (int(x), int(y)), int(radius),
                 (0, 255, 255), 2)
            cv2.circle(frame, center, 5, (0, 0, 255), -1)
            pts.appendleft(center)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

webcam.release()
cv2.destroyAllWindows()
edit retag flag offensive close merge delete

Comments

1

Put this inside of while block.

while(True):
    :
    :
    :
    :                     
    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
supra56 gravatar imagesupra56 ( 2018-10-31 04:06:36 -0600 )edit