【问题标题】:How to remove border components in Python 2.7 using Opencv如何使用 Opencv 在 Python 2.7 中删除边框组件
【发布时间】:2015-06-10 12:08:36
【问题描述】:

我想删除接触图像边框的组件。

我正在使用 OpenCV 2.4.10 和 Python 2.7。

我已经完成了图像的 HSV 转换和 THRESHOLD_BINARY,接下来我要删除与图像边界接触的组件(对象)。

这里在 Matlab 中解释过 - http://blogs.mathworks.com/steve/2007/09/04/clearing-border-components/

但我想在 Python 中使用 OpenCV。

请解释一下代码。

【问题讨论】:

    标签: python-2.7 opencv


    【解决方案1】:

    openCV 中没有直接的方法可以做到这一点。您可以使用 floodFill 方法编写一个函数,并将边界像素作为种子点进行循环。

    floodFill(dstImg,seed,Scalar (0));

    地点:

    dstImg :移除边框的输出。

    种子 : [(x,y) 点] 所有边框坐标

    Scalar(0) :如果找到指向种子点的连接区域,则要填充的颜色。因此 (0) 你的情况是将其填充为黑色。

    示例:

    int totalRows = srcImg.rows;
    int totalCols = srcImg.cols;
    int strt = 0, flg = 0;
    int iRows = 0, jCols = 0;
    while (iRows < srcImg.rows)
    {
        if (flg ==1)
            totalRows = -1;
        Point seed(strt,iRows);     
        iRows++;
        floodFill(dstImg,seed,Scalar (0));
        if (iRows == totalRows)
        {
            flg++;
            iRows = 0;
            strt = totalCols - 1;
        }
    }       
    

    类似地对列进行修改。 希望对您有所帮助。

    【讨论】:

    • 谢谢 sriram 的回复,你能告诉我使用 cv2 替换边框组件的简单代码吗?函数以及如何使用这个floodFill
    • 答案已用代码更新...!您还需要为列添加类似的代码。尝试自己实现...
    【解决方案2】:

    不是很优雅,但您可以将每个轮廓包围在一个边界矩形中,并测试该矩形的坐标是落在图像边界上还是之外(im)

    for c in contours:
        include = True  
        # omit this contour if it touches the edge of the image
        x,y,w,h = cv2.boundingRect(c)       
        if x <= 1 or y <=1:
            include = False                 
        if x+w+1 >= im.shape[1] or y+h+1 >= im.shape[0]:
            include = False
        # draw the contour
        if include == True:
            cv2.drawContours(im, [c], -1, (255, 0, 255), 2)
    

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2016-04-27
      相关资源
      最近更新 更多