当前位置:  开发笔记 > 编程语言 > 正文

OpenCV - 正确使用cv2.approxPolyDP()

如何解决《OpenCV-正确使用cv2.approxPolyDP()》经验,为你挑选了1个好方法。

我试图使用提取图像中轮廓的近似值cv2.approxPolyDP().这是我正在使用的图像:

英国地图

我的代码试图隔离主岛并定义和绘制轮廓近似和轮廓外壳.我绘制了以绿色找到的轮廓,近似为红色:

import numpy as np
import cv2

# load image and shrink - it's massive
img = cv2.imread('../data/UK.png')
img = cv2.resize(img, None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC)

# get a blank canvas for drawing contour on and convert img to grayscale
canvas = np.zeros(img.shape, np.uint8)
img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# filter out small lines between counties
kernel = np.ones((5,5),np.float32)/25
img2gray = cv2.filter2D(img2gray,-1,kernel)

# threshold the image and extract contours
ret,thresh = cv2.threshold(img2gray,250,255,cv2.THRESH_BINARY_INV)
im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)


# find the main island (biggest area)
cnt = contours[0]
max_area = cv2.contourArea(cnt)

for cont in contours:
    if cv2.contourArea(cont) > max_area:
        cnt = cont
        max_area = cv2.contourArea(cont)

# define main island contour approx. and hull
perimeter = cv2.arcLength(cnt,True)
epsilon = 0.01*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)

hull = cv2.convexHull(cnt)

# cv2.isContourConvex(cnt)

cv2.drawContours(canvas, cnt, -1, (0, 255, 0), 3)
cv2.drawContours(canvas, approx, -1, (0, 0, 255), 3)
## cv2.drawContours(canvas, hull, -1, (0, 0, 255), 3) # only displays a few points as well.

cv2.imshow("Contour", canvas)
k = cv2.waitKey(0)

if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()

以下是生成的图像:

在此输入图像描述

第一幅图像以绿色绘制轮廓.第二个用红色绘制近似值 - 如何将此近似值绘制为连续闭合曲线?

该文件是不是非常清楚,无论是教程,但我的理解是,cv2.approxPolyDP()应该定义一个连续,封闭的曲线,这是我应该能够绘制cv2.drawContours().那是对的吗?如果是这样,我做错了什么?



1> avtomaton..:

问题只在于可视化:drawContours期望轮廓的数组(在python的情况下为list),而不仅仅是一个numpy数组(从中返回approxPolyDP).

解决方案如下:更换

cv2.drawContours(canvas, approx, -1, (0, 0, 255), 3)

cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 3)

推荐阅读
保佑欣疼你的芯疼
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有