0
0
0
1. 云栖社区>
2. 博客>
3. 正文

基于颜色特性的目标识别方法

wayne_dream 2018-07-14 21:56:00 浏览597

HSV介绍

RGB2HSV

3.捕获目标代码

• Python3.6.5
• Pycharm
• win10
``````import cv2
import numpy as np

capture = cv2.VideoCapture(0)
lower_blue = np.array([90, 110, 110])
upper_blue = np.array([140, 255, 255])
# 确定目标物体的HSV范围 此范围为蓝色
while(True):

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

cv2.imshow('frame', frame)
cv2.imshow('res', res)
if cv2.waitKey(1) == ord('q'):
break
``````

4.锁定目标，并获取目标质心代码

``````from collections import deque
import numpy as np
import cv2
import time

Lower = np.array([100, 43, 46])
Upper = np.array([130, 255, 255])
# 定义目标颜色HSV的范围

mybuffer = 64
pts = deque(maxlen=mybuffer)
camera = cv2.VideoCapture(0)
time.sleep(2)

while True:
if not ret:
print('No Camera')
break
# frame = imutils.resize(frame, width=600)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 根据阈值构建掩膜
# 腐蚀操作
# 膨胀操作，其实先腐蚀再膨胀的效果是开运算，去除噪点
# 轮廓检测
# 初始化目标轮廓质心
center = None
# 如果存在轮廓
if len(cnts) > 0:
# 找到面积最大的轮廓
c = max(cnts, key=cv2.contourArea)
# 确定面积最大的轮廓的外接圆
# 计算轮廓的矩
M = cv2.moments(c)
# 计算质心
center = (int(M["m10"]/M["m00"]), int(M["m01"]/M["m00"]))

if 80 > radius > 20:
cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
cv2.circle(frame, center, 5, (0, 0, 255), -1)
# 把质心添加到pts中，并且是添加到列表左侧
pts.appendleft(center)

cv2.imshow('Frame', frame)
# 键盘检测，检测到esc键退出
k = cv2.waitKey(5)&0xFF
if k == 27:
break
# 摄像头释放
camera.release()
# 销毁所有窗口
cv2.destroyAllWindows()
``````

wayne_dream
+ 关注