import cv2
import numpy as np
cap = cv2.VideoCapture(0)
cap.set(3, 640) # width=1920
cap.set(4, 480) # height=1080
# HSV红,绿,蓝,黄
lower_red1 = np.array([0, 170, 50])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([170, 150, 50])
upper_red2 = np.array([180, 255, 255])
lower_green = np.array([35, 70, 50])
upper_green = np.array([90, 255, 255])
lower_blue = np.array([90, 70, 50])
upper_blue = np.array([130, 255, 255])
lower_yellow = np.array([15, 70, 50])
upper_yellow = np.array([35, 255, 255])
center_x = 0
center_y = 0
shape = 0
while True:
ret, frame = cap.read()
# 如果帧读取失败,则退出循环
if not ret:
break
# 处理帧,查找红色形状
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
mask = mask1 + mask2
cv2.imshow('mask', mask)
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
# 查找最大的轮廓
cnt = max(contours, key=cv2.contourArea)
# 计算各个轮廓包围的面积
area = cv2.contourArea(cnt)
if area > 5000:
# 计算轮廓中心距
mm = cv2.moments(cnt)
if mm['m00'] != 0:
center_x = int(mm['m10'] / mm['m00'])
center_y = int(mm['m01'] / mm['m00'])
print(center_x, center_y)
else:
continue
epsilon = 0.035 * cv2.arcLength(cnt, True) # 多边形拟合的距离参数,下一个函数要用到。原理见代码后链接
approx = cv2.approxPolyDP(cnt, epsilon, True) # 轮廓近似。将圆润曲线折线化,以此得到该图像的角点坐标。
# 画轮廓线(蓝色)
# cv2.drawContours(frame, cnt, -1, (255, 0, 0), 3)
# # 画近似折线 (红色)
# cv2.polylines(frame, [approx], True, (0, 0, 255), 2)
# # 利用一个矩形将检测目标圈起来(绿色)
# x, y, w, h = cv2.boundingRect(approx)
# cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 得到角点数量
objCor = len(approx)
if objCor == 3:
shape = 1
elif objCor == 4:
shape = 2
elif objCor > 4:
shape = 3
else:
shape = 0
cv2.imshow('frame', frame)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
cap.release()
opencv识别红色色块及形状
最新推荐文章于 2024-04-26 08:52:18 发布