OpenCV,cv2.approxPolyDP()在闭合轮廓上绘制双线 [英] OpenCV, cv2.approxPolyDP() Draws double lines on closed contour

查看:997
本文介绍了OpenCV,cv2.approxPolyDP()在闭合轮廓上绘制双线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create some polygons out of this mask:

图片1-遮罩

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

So i created these contours with openCV findcontours():

图片2-轮廓

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

When creating polygons I get these polygons:

图片3-多边形

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

As you can see some polygons are drawn using double lines. How do I prevent this?

查看我的代码:

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")

推荐答案

问题根源是 Canny边缘检测:

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

After applying edge detection you are getting two contours for every original contour - one outside the edge and one inside the edge (and other weird stuff).

您可以通过应用findContours来解决它,而无需使用Canny.

You may solve it by applying findContours without using 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")


结果:


Result:

这篇关于OpenCV,cv2.approxPolyDP()在闭合轮廓上绘制双线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆