opencv填充未完全关闭的轮廓

opencv填充未完全关闭的轮廓

本文介绍了python opencv填充未完全关闭的轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用openCV找到给定图像的外部轮廓并填充它。
我用作输入的图像是附带的裤子图像。问题是,有时(如附图中)轮廓没有完全关闭,然后我无法填充它。在这种情况下我该怎么办?
请参阅下面的代码。

I use openCV to find the external contour of a given image and fill it.The images I use as input are images of pants like the one attached. The problem is that sometimes (like in the attached image) the contour is not completely closed and then I can't fill it. What can I do in this case?Please see code below.

谢谢,李

from PIL import Image
import os
import numpy
import bs4
import scipy
import cv2

image_obj_original = cv2.imread(image_file)
image_name = os.path.split(image_file)[-1]
name, extension = os.path.splitext(image_name)

# normalize to a standard size
image_obj = cv2.resize(image_obj_original, STANDARD_SIZE)

imWithBorder = cv2.copyMakeBorder(image_obj, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=[255, 255, 255])
# convert to grey-scale
greyscale_image = cv2.cvtColor(imWithBorder,cv2.COLOR_BGR2GRAY)

# get canny edges
canny_edges = cv2.Canny(greyscale_image, 1, 255)

h, w = canny_edges.shape[:2]
contours0, hierarchy = cv2.findContours( canny_edges.copy(), cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE)

contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0]
vis = numpy.zeros((h, w, 3), numpy.uint8)
cv2.drawContours(vis,contours,0,255,-1)
vis = cv2.bitwise_not(vis)
cv2.imshow('image', vis)


推荐答案

我同意Canny有点烦人在OpenCV中并不总是关闭对象轮廓中的最后一个像素,这会阻止您找到一个闭合轮廓。我用来解决这个问题的解决方法是使用关闭形态操作:

I agree that it is somewhat annoying that Canny in OpenCV is not always closing one last pixel in contour of object, and that prevent you from finding one closed contour. The workaround that I used to solve this problem is use of "close" morphological operation:

dilate(canny_edges, canny_edges, Mat());
erode(canny_edges, canny_edges, Mat());

任何解决方法都不完美,但它确实解决了问题。

As any workaround it is not perfect but it does solves the problem.

这篇关于python opencv填充未完全关闭的轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:29