如何用Python调用OpenCV读取图片轮廓
时间: 2023-05-26 15:06:22 浏览: 59
可以按照以下步骤使用Python调用OpenCV读取图片轮廓:
1. 导入必要的库
```python
import cv2
import numpy as np
```
2. 读取图片并将其转换为灰度图像
```python
img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
3. 预处理图像
```python
# 使用高斯平滑过滤器平滑图像
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# 使用Canny边缘检测算法检测边缘
edges = cv2.Canny(blur, 100, 200)
```
4. 查找轮廓
```python
# 找到轮廓
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
```
5. 展示结果
```python
# 展示结果
cv2.imshow("Contours", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```python
import cv2
import numpy as np
# 读取图片并转换为灰度图像
img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 预处理图像
blur = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blur, 100, 200)
# 查找轮廓
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
# 展示结果
cv2.imshow("Contours", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```