opencv检测矩形python
时间: 2025-01-14 08:08:44 浏览: 48
### 使用Python和OpenCV进行矩形检测
#### 安装必要的库
为了能够顺利运行代码,需要确保已经安装了`opencv-python`库。可以使用以下命令来完成安装:
```bash
pip install opencv-python
```
#### 加载并预处理图像
在开始矩形检测之前,通常会对输入图片做一些基本的预处理工作,比如灰度化、高斯模糊等操作,这有助于提高后续特征提取的效果。
```python
import cv2
import numpy as np
# 读取图像文件
image = cv2.imread('example.jpg')
# 将彩色图像转为灰度图
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 应用高斯平滑减少噪声干扰
blurred_gray_image = cv2.GaussianBlur(gray_image, (5, 5), 0)[^5]
```
#### 边缘检测与形态学运算
接下来,通过Canny算法获取图像中的边缘信息,并对其进行闭合填充以形成完整的轮廓结构。
```python
# Canny Edge Detection
edges = cv2.Canny(blurred_gray_image, threshold1=30, threshold2=90)
# 形态学膨胀使断开的部分连接起来
kernel = np.ones((5, 5), dtype=np.uint8)
closed_edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
```
#### 轮廓查找及筛选
利用findContours函数找到所有的封闭区域,再从中挑选出近似于四边形的对象作为候选矩形。
```python
contours, _ = cv2.findContours(closed_edges.copy(), mode=cv2.RETR_EXTERNAL,
method=cv2.CHAIN_APPROX_SIMPLE)
rectangles = []
for contour in contours:
perimeter = cv2.arcLength(contour, closed=True)
approximated_contour = cv2.approxPolyDP(contour, epsilon=0.04 * perimeter, closed=True)
if len(approximated_contour) == 4 and \
cv2.contourArea(contour) > 100: # 过滤掉太小的区域
rectangles.append(approximated_contour)
```
#### 计算矩形属性
对于每一个满足条件的矩形,还可以进一步计算它的几何特性,例如中心位置、旋转角度等。
```python
def get_rectangle_properties(rectangle):
rect = cv2.minAreaRect(rectangle)
box = cv2.boxPoints(rect)
box = np.intp(box)
center_x, center_y = int(rect[0][0]), int(rect[0][1])
angle_of_rotation = abs(rect[-1])
return {
'center': (center_x, center_y),
'rotation_angle': angle_of_rotation,
'vertices': box.tolist()
}
properties_list = [get_rectangle_properties(r) for r in rectangles]
# 打印所有发现的矩形及其属性
for prop in properties_list:
print(f"Center at {prop['center']}, Rotated by {prop['rotation_angle']} degrees.")
```
以上就是一种较为通用的方式来进行矩形对象的自动识别过程[^1]。当然,在具体应用场景下还需要针对实际情况调整参数设置,优化性能表现。
阅读全文
相关推荐


















