Skip to content

Instantly share code, notes, and snippets.

@smeschke
Created August 5, 2016 04:17
Show Gist options
  • Save smeschke/1f9a5835d0bbff6d879e320ed3223e3b to your computer and use it in GitHub Desktop.
Save smeschke/1f9a5835d0bbff6d879e320ed3223e3b to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
kernel = np.ones((8,8),np.uint8)
while(1):
# Take each frame
_, frame = cap.read()
frame = cv2.flip(frame,1)
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of green color in HSV
lower_blue = np.array([50,50,50])
upper_blue = np.array([90,255,255])
# Threshold the HSV image to get only green colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask= mask)
a,b = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in a:
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
if radius > 20:
radius = int(radius)
cv2.circle(frame,center,radius,(0,120,255),-1)
cv2.line(frame, (center[0]-50,center[1]), (center[0]+50,center[1]), (0,0,0),3)
cv2.line(frame, (center[0],center[1]-50), (center[0],center[1]+50), (0,0,0),3)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
#cv2.imshow('open',opening)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment