Tracking a white ball in a white background (Python / OpenCV)

I am using OpenCV in Python 3 to define a white / black ball on a white field and give it accurate (x, y, radius) and color.

I use the cv2.Canny () and cv2.findContours () function to find it, but the problem in cv2.Canny () doesn't always detect the full circle shape (most of the time only 3/4 of the circle). So when I use cv2.findContours () it doesn't define it as Contour.

Please look:

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 there is a function that completes the circle shape so I can detect it?

+3


source to share


2 answers


I would suggest that you apply some intermediate color filtering before using canny detection. This ensures that canny edge detection occurs at a well-defined border between the ball image and the field.

Here is the python code that uses the trackballs so you can adjust 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))

      

+2


source


You can use cv.HoughCircles to estimate the best matching full circle. The nice thing with tracking balls is that the ball will always appear as a circle in the image, regardless of the camera angle.



+1


source







All Articles