pythonc++opencvshapestrackball

Tracking white ball in white background (Python/OpenCV)


i'm using OpenCV in Python 3 to detect a white/black ball on a white field and give it's exact (x,y,radius) and color.

I use the function cv2.Canny() and cv2.findContours() to find it but the problem is cv2.Canny() dont's always detect the complete shape of the circle (most of time only 3/4 of the circle). So when i use cv2.findContours() it don't detect it as a Contour.

Please see :

image 1 and image 2

This is the most important code:

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 10, 40) # 10 and 40 to be more perceptive
contours_canny= cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]

After that i use: approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)

So if you can help me find a solution that would be great! Maybe is there a function that complete the shape of the circle so i can detect it?


Solution

  • What I would suggest is that you apply some intermediate colour filtering before using canny detection. This will ensure that the canny edge detection takes place on a well defined border between the ball image and the field.

    Here is a python code that uses trackbars for you to be able to customize the color threshold:

    cv2.namedWindow('temp')
    cv2.createTrackbar('bl', 'temp', 0, 255, nothing)
    cv2.createTrackbar('gl', 'temp', 0, 255, nothing)
    cv2.createTrackbar('rl', 'temp', 0, 255, nothing)
    cv2.createTrackbar('bh', 'temp', 255, 255, nothing)
    cv2.createTrackbar('gh', 'temp', 255, 255, nothing)
    cv2.createTrackbar('rh', 'temp', 255, 255, nothing)
    
    bl_temp=cv2.getTrackbarPos('bl', 'temp')
    gl_temp=cv2.getTrackbarPos('gl', 'temp')
    rl_temp=cv2.getTrackbarPos('rl', 'temp')
    
    bh_temp=cv2.getTrackbarPos('bh', 'temp')
    gh_temp=cv2.getTrackbarPos('gh', 'temp')
    rh_temp=cv2.getTrackbarPos('rh', 'temp')
    thresh=cv2.inRange(frame,(bl_temp,gl_temp,rl_temp),(bh_temp,gh_temp,rh_temp))