opencv findcontours如何找到内轮廓
时间: 2023-10-08 18:08:57 浏览: 127
内轮廓是指轮廓内部的孔洞或空洞。要找到内轮廓,可以使用findContours函数中的参数mode和method来指定轮廓的类型和逼近方法。
首先,将mode设置为CV_RETR_CCOMP,这将找到所有轮廓,包括内轮廓。然后,将method设置为CV_CHAIN_APPROX_SIMPLE,这将使用简单的逼近方法来减少轮廓上的点数。
接下来,对于每个找到的轮廓,可以检查其层级关系,如果其父轮廓是外轮廓,则说明它是一个内轮廓。
下面是一个示例代码:
```
import cv2
# 读取图像
img = cv2.imread("image.png")
# 灰度化和二值化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# 遍历轮廓
for i in range(len(contours)):
# 如果是内轮廓
if hierarchy[0][i][3] != -1:
# 绘制轮廓
cv2.drawContours(img, contours, i, (0, 255, 0), 2)
# 显示结果
cv2.imshow("Result", img)
cv2.waitKey(0)
```
阅读全文
相关推荐















