opencv python 寻找矩形
时间: 2024-08-10 19:01:42 浏览: 26
在 OpenCV 中,Python 版本可以使用 `cv2.findContours` 函数以及相关的形状检测算法来寻找图像中的矩形。以下是一个基本步骤:
1. **读取图像**:
使用 `cv2.imread()` 函数加载图像。
```python
import cv2
image = cv2.imread('image.jpg')
```
2. **转换为灰度图像**(如果需要):
如果你想处理的是灰度图像,可以省略这一步,否则建议转换以简化分析。
```python
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
```
3. **边缘检测**:
对图像应用边缘检测算子,如 Canny 或者简单的阈值化。
```python
edges = cv2.Canny(gray_image, threshold1, threshold2)
```
4. **找到轮廓**:
运行轮廓检测算法并得到所有轮廓。
```python
contours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
```
5. **筛选矩形**:
遍历轮廓列表,对于每个轮廓,检查是否接近矩形形状。可以计算轮廓的边界框 (bounding box),并查看其宽高比接近于 1(正方形)还是接近 4(长方形)。例如,可以使用 `minAreaRect` 和 `minEnclosingCircle` 函数来判断。
```python
for contour in contours:
x,y,w,h = cv2.boundingRect(contour)
aspect_ratio = w/h
if aspect_ratio >= 0.9 and aspect_ratio <= 1.1: # 矩形范围内的宽高比
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect) # 转换为点坐标
# 绘制矩形
cv2.drawContours(image, [box], 0, (0,255,0), 2)
```
6. **显示结果**:
最后,显示包含矩形区域的原始图像。
```python
cv2.imshow("Image with Rectangles", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```