-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathWhackAMoleOpenCV.py
More file actions
53 lines (45 loc) · 1.88 KB
/
WhackAMoleOpenCV.py
File metadata and controls
53 lines (45 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#Import OpenCV
import cv2
#Import Numpy
import numpy as np
"""OpenCV portion of Gual-a-Mole! code"""
camera_feed = cv2.VideoCapture(0)
def color_tracking(child):
while(1):
_,frame = camera_feed.read()
#Convert the current frame to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
#Define the threshold for finding a blue object with hsv
lower_blue = np.array([100,100,100])
upper_blue = np.array([140,255,255])
#Create a binary image, where anything blue appears white and everything else is black
mask = cv2.inRange(hsv, lower_blue, upper_blue)
#Get rid of background noise using erosion and fill in the holes using dilation and erode the final image on last time
element = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
mask = cv2.erode(mask,element, iterations=2)
mask = cv2.dilate(mask,element,iterations=2)
mask = cv2.erode(mask,element)
#Create Contours for all blue objects
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
maximumArea = 0
bestContour = None
for contour in contours:
currentArea = cv2.contourArea(contour)
if currentArea > maximumArea:
bestContour = contour
maximumArea = currentArea
#Create a bounding box around the biggest blue object
if bestContour is not None:
x,y,w,h = cv2.boundingRect(bestContour)
cv2.rectangle(frame, (x,y),(x+w,y+h), (0,0,255), 3)
# sends the center of the rectangle to the parent
child.send([x+w/2,y+h/2])
#Show the original camera feed with a bounding box overlayed
cv2.imshow('frame',frame)
#Show the contours in a seperate window
cv2.imshow('mask',mask)
#Use this command to prevent freezes in the feed
k = cv2.waitKey(5) & 0xFF
#If escape is pressed close all windows
if k == 27:
break