OpenCV cv2.minAreaRect() 函数详解:计算轮廓最小外接矩形
OpenCV cv2.minAreaRect() 函数详解:计算轮廓最小外接矩形
cv2.minAreaRect(contour) 是一个 OpenCV 函数,用于计算给定轮廓的最小外接矩形。
参数:
contour: 轮廓,一个由点组成的 Numpy 数组,表示图像中的连续区域。
返回值:
bounding_box: 一个元组,包含矩形的中心点坐标、宽度、高度和旋转角度。
解释:
这个函数返回能够完全包含轮廓的最小旋转矩形。旋转角度表示矩形相对于水平轴的旋转角度,以度为单位。
示例:
import cv2
import numpy as np
# 加载图像
image = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 进行边缘检测
edges = cv2.Canny(gray, 50, 150)
# 查找轮廓
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 选择一个轮廓
contour = contours[0]
# 计算最小外接矩形
bounding_box = cv2.minAreaRect(contour)
# 获取矩形的中心点、宽度、高度和旋转角度
center = bounding_box[0]
width = bounding_box[1][0]
height = bounding_box[1][1]
angle = bounding_box[2]
# 在图像上绘制矩形
box = cv2.boxPoints(bounding_box)
box = np.int0(box)
cv2.drawContours(image, [box], -1, (0, 0, 255), 2)
# 显示图像
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
应用场景:
- 识别和定位图像中的物体
- 计算物体的面积和周长
- 对图像进行几何变换
总结:
cv2.minAreaRect() 函数是一个强大的工具,可用于计算轮廓的最小外接矩形。它在许多图像处理应用中都非常有用。
原文地址: https://www.cveoy.top/t/topic/mRka 著作权归作者所有。请勿转载和采集!