温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - OpenCV, cv2.approxPolyDP() Draws double lines on closed contour
mask opencv opencv-contour polygon python

python - OpenCV,cv2.approxPolyDP()在闭合轮廓上绘制双线

发布于 2020-05-28 16:21:19

我想从此蒙版创建一些多边形:

图片1-遮罩 面具

所以我用openCV findcontours()创建了这些轮廓:

图片2-轮廓

等高线

创建多边形时,我得到了这些多边形:

图片3-多边形 多边形

如您所见,某些多边形是使用双线绘制的。我该如何预防?

看我的代码:

import glob
from PIL import Image
import cv2
import numpy as np


# Let's load
image = cv2.imread(path + "BigOneEnhanced.tif") 

# Grayscale 
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 

# Find Canny edges 
edged = cv2.Canny(gray, 30, 200) 

# Finding Contours 
contours, hierarchy = cv2.findContours(edged,  
    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1) 

canvas = np.zeros(image.shape, np.uint8)

# creating polygons from contours

polygonelist = []

for cnt in contours:

    # define contour approx
    perimeter = cv2.arcLength(cnt,True)
    epsilon = 0.005*cv2.arcLength(cnt,True)
    approx = cv2.approxPolyDP(cnt,epsilon,True)


    polygonelist.append(approx)

cv2.drawContours(canvas, polygonelist, -1, (255, 255, 255), 3)


imgB = Image.fromarray(canvas)
imgB.save(path + "TEST4.png")

查看更多

提问者
B. Bram
被浏览
22
Rotem 2020-03-13 00:28

问题来源是Canny边缘检测:

应用边缘检测后,您将为每个原始轮廓得到两个轮廓-一个在边缘外部,一个在边缘内部(以及其他奇怪的东西)。

您可以通过使用findContours而不使用来解决它Canny

这是代码:

import glob
from PIL import Image
import cv2
import numpy as np

path = ''

# Let's load
#image = cv2.imread(path + "BigOneEnhanced.tif") 
image = cv2.imread("BigOneEnhanced.png") 

# Grayscale 
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 

# Apply threshold (just in case gray is not binary image).
ret, thresh_gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# Find Canny edges 
#edged = cv2.Canny(gray, 30, 200)

# Finding Contours cv2.CHAIN_APPROX_TC89_L1
#contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

contours, hierarchy = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

canvas = np.zeros(image.shape, np.uint8)

# creating polygons from contours
polygonelist = []

for cnt in contours:
    # define contour approx
    perimeter = cv2.arcLength(cnt, True)
    epsilon = 0.005*perimeter #0.005*cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, epsilon, True)

    polygonelist.append(approx)

cv2.drawContours(canvas, polygonelist, -1, (255, 255, 255), 3)

imgB = Image.fromarray(canvas)
imgB.save(path + "TEST4.png")

结果:
在此处输入图片说明