gpt4 book ai didi

python - OpenCV:在不使用 RETR_EXTERNAL 的情况下删除形状轮廓上的双轮廓

转载 作者:行者123 更新时间:2023-12-04 14:49:01 27 4
gpt4 key购买 nike

Open CV 将为多边形的轮廓注册内部和外部轮廓。

运行下面的测试代码

import cv2
import numpy as np

def extract_contours():
path = 'test.png'
blank = np.zeros((184,184,3), np.uint8)
blank[:] = (255,255,255)
raw = cv2.imread(path, cv2.IMREAD_UNCHANGED)
raw = 255-raw
img = cv2.cvtColor(raw, cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 400:
approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)
cv2.drawContours(blank, [approx], 0, (0, 0, 255), 1)

cv2.imwrite('contours.png', blank)

extract_contours()

在图片上

hollow square

将在外边缘和内边缘产生两组轮廓,如图所示

double contours

有没有什么快速的方法可以将两组轮廓折叠成一个轮廓,最好是两者的平均值?总体而言,我对 CV2 和计算机视觉还很陌生,所以我不知道很多技巧。我宁愿不使用 RETR_EXTERNAL,因为我不想错过任何嵌套形状。

最佳答案

您可以使用您定义的hierarchy 变量(调用cv2.findContours 方法时) 来确定轮廓是否在外部轮廓或内部:

import cv2
import numpy as np

def extract_contours():
path = 'test.png'
blank = np.zeros((184, 184, 3), np.uint8)
blank[:] = (255, 255, 255)
raw = cv2.imread(path, cv2.IMREAD_UNCHANGED)
raw = 255 - raw
img = cv2.cvtColor(raw, cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt, hrc in zip(contours, hierarchy[0]):
area = cv2.contourArea(cnt)
if area > 400:
approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)
if hrc[2] < 0:
cv2.drawContours(blank, [approx], 0, (0, 0, 255), 1)
elif hrc[3] < 0:
cv2.drawContours(blank, [approx], 0, (0, 255, 0), 1)

cv2.imwrite('contours.png', blank)

extract_contours()

结果图像:

enter image description here

在外部和内部轮廓之间绘制轮廓:

import cv2
import numpy as np

def extract_contours():
path = 'test.png'
blank = np.zeros((184, 184, 3), np.uint8)
blank[:] = (255, 255, 255)
raw = cv2.imread(path, cv2.IMREAD_UNCHANGED)
raw = 255 - raw
img = cv2.cvtColor(raw, cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
exte = None
inte = None
for cnt, hrc in zip(contours, hierarchy[0]):
area = cv2.contourArea(cnt)
if area > 400:
approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)
if hrc[2] < 0:
exte = approx.squeeze()
elif hrc[3] < 0:
inte = approx.squeeze()
exte = exte[np.lexsort(exte.T)]
inte = inte[np.lexsort(inte.T)]
box = cv2.convexHull((exte[exte[:, 0].argsort()] + inte[inte[:, 0].argsort()]) // 2)
cv2.drawContours(blank, [box], -1, (0, 0, 255), 1)
cv2.imwrite('contours.png', blank)

extract_contours()

结果图像:

enter image description here

关于python - OpenCV:在不使用 RETR_EXTERNAL 的情况下删除形状轮廓上的双轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69369615/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com