自选合适的图像(图中需要有多个轮廓),实现轮廓检测,并计算轮廓的面积和宽高比,最后找出面积最大的轮廓,在原图中用外接矩形(正矩形)圈出来,找出宽高比最大的轮廓,在原图中用最小外接矩形(旋转矩形)圈出来
时间: 2024-04-09 21:33:41 浏览: 129
以下是一个使用 OpenCV 库进行轮廓检测、计算轮廓面积和宽高比,并在原图中圈出最大面积轮廓和最大宽高比轮廓的示例代码:
```python
import cv2
# 读取图像
image = cv2.imread('your_image.jpg')
# 将图像转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 对图像进行二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, 0)
# 查找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 初始化最大面积和宽高比变量
max_area = 0
max_aspect_ratio = 0
max_area_contour = None
max_aspect_ratio_contour = None
# 遍历轮廓
for contour in contours:
# 计算轮廓面积
area = cv2.contourArea(contour)
# 计算轮廓的外接矩形
x, y, w, h = cv2.boundingRect(contour)
# 计算宽高比
aspect_ratio = float(w) / h
# 更新最大面积轮廓
if area > max_area:
max_area = area
max_area_contour = contour
# 更新最大宽高比轮廓
if aspect_ratio > max_aspect_ratio:
max_aspect_ratio = aspect_ratio
max_aspect_ratio_contour = contour
# 在原图中用外接矩形圈出最大面积轮廓
x, y, w, h = cv2.boundingRect(max_area_contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 在原图中用最小外接矩形圈出最大宽高比轮廓
rect = cv2.minAreaRect(max_aspect_ratio_contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(image, [box], 0, (0, 0, 255), 2)
# 显示结果图像
cv2.imshow('Result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请将代码中的 `your_image.jpg` 替换为您自己的图像路径。执行该代码后,将显示带有圈出最大面积轮廓和最大宽高比轮廓的原始图像。
阅读全文
相关推荐


















