open cv调用摄像头 识别 黑色矩形 输出矩形的4个顶点坐标x1y1;x2y2;x3y3;x4y4 的代码
下面是使用OpenCV调用摄像头进行黑色矩形识别并输出4个顶点坐标的代码:
import cv2
import numpy as np
def detect_black_rectangle(frame):
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 对图像进行二值化处理
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 查找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# 计算轮廓的周长
perimeter = cv2.arcLength(contour, True)
# 根据周长进行近似处理
approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
# 如果近似得到的轮廓是矩形且颜色为黑色,则输出顶点坐标
if len(approx) == 4 and cv2.contourArea(approx) > 1000 and cv2.isContourConvex(approx):
if cv2.mean(frame, mask=approx)[0] < 50:
x1, y1 = approx[0][0]
x2, y2 = approx[1][0]
x3, y3 = approx[2][0]
x4, y4 = approx[3][0]
return (x1, y1), (x2, y2), (x3, y3), (x4, y4)
return None
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头帧
ret, frame = cap.read()
if ret:
# 调用函数进行矩形识别
result = detect_black_rectangle(frame)
if result is not None:
# 绘制矩形
cv2.polylines(frame, [np.array(result)], True, (0, 255, 0), 2)
# 输出顶点坐标
cv2.putText(frame, f"x1,y1: {result[0]}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(frame, f"x2,y2: {result[1]}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(frame, f"x3,y3: {result[2]}", (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(frame, f"x4,y4: {result[3]}", (10, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
# 显示帧
cv2.imshow("Frame", frame)
# 按下ESC键退出
if cv2.waitKey(1) == 27:
break
# 释放摄像头
cap.release()
# 关闭窗口
cv2.destroyAllWindows()
这段代码会打开摄像头,并实时检测帧中的黑色矩形。如果检测到黑色矩形,则会在帧中绘制矩形,并在图像上方显示矩形的4个顶点坐标。按下ESC键可以退出程序。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/iush 著作权归作者所有。请勿转载和采集!