在二进制对象内填充孔 [英] Filling holes inside a binary object

查看:188
本文介绍了在二进制对象内填充孔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,在黑色硬币内填充白洞,这样我就可以只有0-255二进制图像和填充的黑色硬币..我使用了中位数滤镜来完成它但是在这种情况下,硬币之间的连接桥增长了经过几次侵蚀后,我们无法识别它们......所以我需要在opencv中使用简单的floodFill方法

I have a problem with filling white holes inside a black coins so that I can have only 0-255 binary image with filled black coins.. I have used Median filter to accomplish it but in that case connection bridge between coins grows and it goes impossible to recognize them after several times of erosion... So I need a simple floodFill like method in opencv

这是我带洞的图像:

编辑:类似函数的floodfill必须填充大组件中的漏洞而不提示X,Y坐标作为种子......

floodfill like function must fill holes in big components without prompting X,Y coordinates as a seed...

编辑:我尝试使用cvDrawContours函数,但我没有填写更大的轮廓。

I tried to use cvDrawContours function but I doesn't fill contours inside bigger ones.

这是我的代码:

        CvMemStorage mem = cvCreateMemStorage(0);
        CvSeq contours = new CvSeq();
        CvSeq ptr = new CvSeq();
        int sizeofCvContour = Loader.sizeof(CvContour.class);

        cvThreshold(gray, gray, 150, 255, CV_THRESH_BINARY_INV);

        int numOfContours = cvFindContours(gray, mem, contours, sizeofCvContour, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
        System.out.println("The num of contours: "+numOfContours); //prints 87, ok

        Random rand = new Random();
        for (ptr = contours; ptr != null; ptr = ptr.h_next()) {
            Color randomColor = new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat());
            CvScalar color = CV_RGB( randomColor.getRed(), randomColor.getGreen(), randomColor.getBlue());
            cvDrawContours(gray, ptr, color, color, -1, CV_FILLED, 8);
        }
        CanvasFrame canvas6  = new CanvasFrame("drawContours");
        canvas6.showImage(gray);

结果:(你可以看到每枚硬币内有黑洞)

Result: (you can see black holes inside each coin)

推荐答案

有两种方法可以做到这一点:

There are two methods to do this:

1)轮廓填充:

首先反转图像,找到图像中的轮廓,用黑色填充并倒转。

First invert the image,find contours in the image, fill it with black and invert back.

des = cv2.bitwise_not(gray)
contour,hier = cv2.findContours(des,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contour:
    cv2.drawContours(des,[cnt],0,255,-1)

gray = cv2.bitwise_not(des)

结果图片:

2)图像开启:

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
res = cv2.morphologyEx(gray,cv2.MORPH_OPEN,kernel)

生成的图像如下:

你可以看到,两种情况都没有太大区别。

You can see, there is no much difference in both the cases.

NB :灰色 - 灰度图像,所有代码在OpenCV-Python中

NB: gray - grayscale image, All codes are in OpenCV-Python

这篇关于在二进制对象内填充孔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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