Python OpenCV 识别视频帧中第二大的黑色矩形
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 将帧转换为灰度图像
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) # 对灰度图像进行二值化处理,反转黑白
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 寻找轮廓
contours = sorted(contours, key=cv2.contourArea, reverse=True) # 按轮廓面积排序
if len(contours) > 1:
second_largest_contour = contours[1] # 获取第二大的轮廓
x, y, w, h = cv2.boundingRect(second_largest_contour) # 获取轮廓的外接矩形
x1, y1 = x, y
x2, y2 = x + w, y
x3, y3 = x + w, y + h
x4, y4 = x, y + h
x_center = (x1 + x2) / 2
y_center = (y1 + y3) / 2
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # 在原始图像上绘制第二大矩形
cv2.imshow('Second Largest Rectangle', frame) # 显示带有矩形的图像
print(f'x1: {x1}, y1: {y1}')
print(f'x2: {x2}, y2: {y2}')
print(f'x3: {x3}, y3: {y3}')
print(f'x4: {x4}, y4: {y4}')
原文地址: https://www.cveoy.top/t/topic/fxxN 著作权归作者所有。请勿转载和采集!