OpenCV2 图像识别:左右矩形检测及最大矩形框坐标获取
下面是一个使用 OpenCV2 识别图像中左右矩形并输出最大矩形框坐标的示例代码:
import cv2
# 读取图像
image = cv2.imread('image.jpg')
# 将图像转为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 二值化处理
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找图像中的轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 用于保存左右矩形的坐标和宽度高度
left_rect = None
right_rect = None
# 遍历所有轮廓
for contour in contours:
# 获取轮廓的边界框
x, y, w, h = cv2.boundingRect(contour)
# 判断矩形是左边还是右边
if x < image.shape[1] / 2:
left_rect = (x, y, w, h)
else:
right_rect = (x, y, w, h)
# 输出左右矩形的坐标和宽度高度
print("Left rectangle:", left_rect)
print("Right rectangle:", right_rect)
# 输出最大矩形框的坐标
if left_rect and right_rect:
max_rect = max(left_rect, right_rect, key=lambda rect: rect[2] * rect[3])
print("Max rectangle:", max_rect)
请确保安装了 OpenCV 库,并将图像文件命名为'image.jpg'并放置在与代码文件相同的目录中。
原文地址: https://www.cveoy.top/t/topic/pGiO 著作权归作者所有。请勿转载和采集!