import cv2
import numpy as np
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)#获取摄像头
cap.set(3,640)
cap.set(4,480)
cap.set(10,100)#调节亮度
myColors = [[2,107,0,19,255,255],
[133,56,0,159,156,255],
[57,76,0,100,255,255]]#颜色列表
#识别色彩
def findColor(img,myColors):
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower = np.array(myColors[0][0:3])#下限
upper = np.array(myColors[0][3:6])#上限
mask = cv2.inRange(imgHSV,lower,upper)
cv2.imshow("img",mask)
while True:
success, img = cap.read()
findColor(img,myColors)
cv2.imshow("video",img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
这个参数能hsv橘色
加上边缘检测,用的是之前调用的弧
import cv2
import numpy as np
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)#获取摄像头
cap.set(3,640)
cap.set(4,480)
cap.set(10,100)#调节亮度
myColors = [[2,107,0,19,255,255],
[133,56,0,159,156,255],
[57,76,0,100,255,255]]#颜色列表
#识别色彩
def findColor(img,myColors):
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
for color in myColors:
lower = np.array(color[0:3])#下限
upper = np.array(color[3:6])#上限
mask = cv2.inRange(imgHSV,lower,upper)
x,y = getContours(mask)
cv2.circle(imgResult,(x,y),10,(255,0,0),cv2.FILLED)
cv2.imshow("str(color[i])",mask)
def getContours(img):
contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)#检测外部轮廓
x,y,w,h = 0,0,0,0
for cnt in contours:
area = cv2.contourArea(cnt)
if area>300:
cv2.drawContours(imgResult,cnt,-1,(255,0,0),3)
peri = cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,0.02*peri,True)
x ,y,w,h = cv2.boundingRect(approx)#xy对象的宽和高
return x+w//2,y
while True:
success, img = cap.read()
imgResult = img.copy()
findColor(img,myColors)
cv2.imshow("video",imgResult)
if cv2.waitKey(1) & 0xFF == ord('q'):
break