| amstrudy |
14-01-2017 19:58 |
Simple Gear Detection
Here is Team 900's very simple gear detection based off of color and area.
Code:
# basic gear detection from HSV
# 1/14/17
# Team 900 Zebracorns
# Author: Anja S
import cv2
import numpy as np
cap = cv2.VideoCapture(1)
kernel = np.ones((5,5),np.uint8)
while(1):
# Take each frame
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Threshold the HSV image
lower = np.array([20, 55, 124])
upper = np.array([48, 255, 247])
mask = cv2.inRange(hsv, lower, upper)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
# Contours
contours = cv2.findContours(closing,cv2.cv.CV_RETR_TREE,cv2.cv.CV_CHAIN_APPROX_SIMPLE)[0]
# Remove contours that don't fit area and HSV constraints
gear_contour = []
for c in contours:
moments = cv2.moments(c)
area = cv2.contourArea(c)
if area < 3000: continue
perim = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.00005*perim, True)
if len(approx) > 20:
gear_contour.append(approx)
for x in range(0, len(gear_contour)):
minX = 10000
minY = 10000
maxX = 0
maxY = 0
cx = (minX + maxX)//2
cy = (minY + maxY)//2
# draw box around gear contour
for y in range(0, len(gear_contour[x])):
if gear_contour[x][y][0][0] < minX:
minX = gear_contour[x][y][0][0]
if gear_contour[x][y][0][1] < minY:
minY = gear_contour[x][y][0][1]
if gear_contour[x][y][0][0] > maxX:
maxX = gear_contour[x][y][0][0]
if gear_contour[x][y][0][1] > maxY:
maxY = gear_contour[x][y][0][1]
if gear_contour:
cv2.drawContours(frame, gear_contour, -1, (255, 0, 0),3)
cv2.rectangle(frame,(minX, minY),(maxX, maxY),(255,255,0),3)
cv2.imshow('frame',frame)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
|