我正在研究一个在白色背景上跟随黑线的线跟随器机器人代码是这样的
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
try:
while(1):
## Read the image
ret, img = cap.read()
#cv2.imshow('image',img)
img = img[160:320,:,:]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,170,255,cv2.THRESH_BINARY_INV)
#Applying Dilation Morphological Operation To Dilate the image
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
dilation = cv2.dilate(thresh, kernel, iterations = 5)
#Apllying Gaussian Bluring Algorithm to reduce the number of contours
blur3 = cv2.medianBlur (dilation,5)
i = 0
contours, hierarchy = cv2.findContours(blur3,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img,contours,-1,(0,255,0),3)
cv2.imshow('image',img)
M = cv2.moments(contours[i])
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
if cx < 190:
print "LEFT"
if cx > 450:
print "RIGHT "
if ((cx > 189) & (cx < 449)):
print "FRONT"
finally:
cap.release()
cv2.destroyAllWindows()
我想在机器人使用相同的相机跟踪线时检测蓝色和红色。
我尝试读取质心center_px = img[cy,cx]
但只读一个像素剂量就可以有效地确定颜色。
有没有其他方法可以做到这一点
我正在使用python2.7和cv2