-
Notifications
You must be signed in to change notification settings - Fork 6
/
6-target.py
70 lines (61 loc) · 2.47 KB
/
6-target.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import numpy as np
import cv2
import time
import os
# This system command loads the right drivers for the Raspberry Pi camera
os.system('sudo modprobe bcm2835-v4l2')
w=480
h=320
my_camera = cv2.VideoCapture(0)
my_camera.set(3,w)
my_camera.set(4,h)
time.sleep(2)
while (True):
success, image = my_camera.read()
image = cv2.flip(image,-1)
image = cv2.GaussianBlur(image,(5,5),0)
image_HSV = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
lower_pink = np.array([166,50,50])
upper_pink = np.array([174,255,255])
mask = cv2.inRange(image_HSV,lower_pink,upper_pink)
mask = cv2.GaussianBlur(mask,(5,5),0)
# findContours returns a list of the outlines of the white shapes in the mask (and a heirarchy that we shall ignore)
# API differences:
# OpenCV 2.x: findContours -> contours, hierarchy
# OpenCV 3.x: findContours -> image, contours, hierarchy
# OpenCV 4.x: findContours -> contours, hierarchy
contours, hierarchy = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2:]
# If we have at least one contour, look through each one and pick the biggest
if len(contours)>0:
largest = 0
area = 0
for i in range(len(contours)):
# get the area of the ith contour
temp_area = cv2.contourArea(contours[i])
# if it is the biggest we have seen, keep it
if temp_area > area:
area = temp_area
largest = i
# Compute the coordinates of the center of the largest contour
coordinates = cv2.moments(contours[largest])
target_x = int(coordinates['m10']/coordinates['m00'])
target_y = int(coordinates['m01']/coordinates['m00'])
# Pick a suitable diameter for our target (grows with the contour)
diam = int(np.sqrt(area)/4)
# draw on a target
cv2.circle(image,(target_x,target_y),diam,(0,255,0),1)
cv2.line(image,(target_x-2*diam,target_y),(target_x+2*diam,target_y),(0,255,0),1)
cv2.line(image,(target_x,target_y-2*diam),(target_x,target_y+2*diam),(0,255,0),1)
cv2.imshow('View',image)
# Esc key to stop, otherwise repeat after 3 milliseconds
key_pressed = cv2.waitKey(3)
if key_pressed == 27:
break
cv2.destroyAllWindows()
my_camera.release()
# due to a bug in openCV you need to call wantKey three times to get the
# window to dissappear properly. Each wait only last 10 milliseconds
cv2.waitKey(10)
time.sleep(0.1)
cv2.waitKey(10)
cv2.waitKey(10)