Skip to content

Instantly share code, notes, and snippets.

@GSE-UP
Last active September 11, 2019 17:36
Show Gist options
  • Save GSE-UP/67e02dd53294cf2511a7c83d8470f710 to your computer and use it in GitHub Desktop.
Save GSE-UP/67e02dd53294cf2511a7c83d8470f710 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
import time
import math
# Read the camera
cap = cv2.VideoCapture(0)
# Define range of colors in HSV
lower = {'Yellow':(15,90,95)}
upper = {'Yellow':(25,220,205)}
# Define color in BGR
color = {'Yellow':(0,255,255)}
while(1):
# Take each frame
_, frame = cap.read()
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Define mask
mask = cv2.inRange(hsv, lower['Yellow'], upper['Yellow'])
# Find contours in the mask and initialize the current (x, y) center of the ball
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
center = None
if len(cnts) > 0:
# Find largest contour in the ball mask
contour = max(cnts, key = cv2.contourArea)
# Get circle info
((x, y), radius) = cv2.minEnclosingCircle(contour)
M = cv2.moments(contour)
if M["m00"] != 0:
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
else:
center = None
if center != None:
# Print position and contour
cv2.putText(frame, 'Yellow' + str(center), (int(x-radius),int(y-radius)), cv2.FONT_HERSHEY_SIMPLEX, 0.6,color['Yellow'],2)
cv2.drawContours(frame, [contour],0,color['Yellow'],2)
res = cv2.bitwise_and(frame,frame,mask= mask)
# Show screens
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
k = cv2.waitKey(1) & 0xFF
if k == ord("q"):
break
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment