Skip to content

Instantly share code, notes, and snippets.

@sourceperl
Created June 14, 2016 15:00
Show Gist options
  • Save sourceperl/e6601c4629c0ab39cc267772ca52f1db to your computer and use it in GitHub Desktop.
Save sourceperl/e6601c4629c0ab39cc267772ca52f1db to your computer and use it in GitHub Desktop.
Track a water bottle cap view by USB cam (use Python2 with open_cv 2 and numpy)
import cv2
import numpy as np
# open_cv track test :
#
# track blue object and check there are in circle area
# for test: object is a blue water bottle cap (color H,S,V = 202 (101 after normalized, 64, 59)
# some class
class Circle(object):
def __init__(self, center, radius):
self.center = center
self.radius = radius
def is_inside(self, pos):
return (pos[0] - self.center[0])**2 + (pos[1] - self.center[1])**2 < self.radius**2
# some vars
center = (0, 0)
i = 0
# link to USB cam /dev/video1
cap = cv2.VideoCapture(1)
# main loop
while True:
# take each frame
_, frame = cap.read()
# convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([92,50, 50])
upper_blue = np.array([112,255,255])
# threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
# find contours in the mask
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
center = (0,0)
radius = 0
# if one or more contour(s) find
if len(cnts) > 0:
# use the larger area
c = max(cnts, key=cv2.contourArea)
# area as a circle
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00']))
# bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask= mask)
# set circle
c1 = Circle((400, 350), 20)
# add cible
cv2.circle(res, center, 5, (0,255,0), -1)
cv2.circle(res, c1.center, c1.radius, (0,255,0), 0)
# check if center is in target and large enough
if radius > 20 and c1.is_inside(center):
print('cap is in circle (#%d)' % i)
i += 1
# display all
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
# manage escape key
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment