opencv 写一段图片孔洞填充
时间: 2023-11-07 07:13:29 浏览: 34
下面是一段使用OpenCV库实现图片孔洞填充的Python代码:
```python
import cv2
import numpy as np
# 读取图片并转换为灰度图
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理,将图像转换为黑白
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找图像中的轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 填充孔洞
for i in range(len(contours)):
cv2.drawContours(thresh, contours, i, 255, -1)
# 显示结果
cv2.imshow('image', img)
cv2.imshow('filled', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
代码中首先读取一张图片并将其转换为灰度图,然后使用二值化处理将图像转换为黑白。接着使用`cv2.findContours()`函数查找图像中的轮廓,这里使用`cv2.RETR_EXTERNAL`参数表示只查找最外层的轮廓。最后使用`cv2.drawContours()`函数将轮廓内部的孔洞填充。最终结果显示原图和填充后的图像。