1 | initial version |
In case someone finds this in a search, I came up with a functional, albeit slow, method.
import cv2
import numpy as np
import serial
cap = cv2.VideoCapture(1)
loc = input('ACM: ')
ser = serial.Serial('/dev/ttyACM'+str(loc), 9600)
while(1):
# Take each frame
_, frame = cap.read()
width = len(frame[0,:])
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Define color range for masking
lower = np.array([110,100,100])
upper = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower, upper)
# Bitwise-AND mask and original image
result = cv2.bitwise_and(frame,frame, mask= mask)
gray = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY)
#(image, max corners, quality level, minimum distance, mask)
corners = cv2.goodFeaturesToTrack(gray,4,0.01,10)
corners = np.int0(corners)
for i in corners:
x_array = []
y_array = []
x,y = i.ravel()
cv2.circle(result,(x,y),3,255,-1)
x_array.append(x)
y_array.append(y)
# Compare the average value of the X position to the midpoint of the frame
# and print its relative location
if (np.mean(x_array) <= int(width/2)):
print 'left'
else:
print 'right'
#cv2.imshow('res',result)
if cv2.waitKey(3) & 0xFF == ord('q'):
break
ser.write(str(chr(2)))
break
cv2.destroyAllWindows()
2 | No.2 Revision |
In case someone finds this in a search, I came up with a functional, albeit slow, method.
import cv2
import numpy as np
import serial
cap = cv2.VideoCapture(1)
loc = input('ACM: ')
ser = serial.Serial('/dev/ttyACM'+str(loc), 9600)
while(1):
# Take each frame
_, frame = cap.read()
width = len(frame[0,:])
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Define color range for masking
lower = np.array([110,100,100])
upper = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower, upper)
# Bitwise-AND mask and original image
result = cv2.bitwise_and(frame,frame, mask= mask)
gray = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY)
#(image, max corners, quality level, minimum distance, mask)
corners = cv2.goodFeaturesToTrack(gray,4,0.01,10)
corners = np.int0(corners)
for i in corners:
x_array = []
y_array = []
x,y = i.ravel()
cv2.circle(result,(x,y),3,255,-1)
x_array.append(x)
y_array.append(y)
# Compare the average value of the X position to the midpoint of the frame
# and print its relative location
if (np.mean(x_array) <= int(width/2)):
print 'left'
else:
print 'right'
#cv2.imshow('res',result)
if cv2.waitKey(3) & 0xFF == ord('q'):
break
ser.write(str(chr(2)))
break
cv2.destroyAllWindows()
cv2.destroyAllWindows()