【问题标题】:How to identify contours within another contour using JavaCV?如何使用 JavaCV 识别另一个轮廓内的轮廓?
【发布时间】:2012-07-12 08:10:24
【问题描述】:

如何识别另一个轮廓内的轮廓?我试图通过许多 OpenCV 教程,但我无法识别它。请问有高手能提供简单的代码解释一下吗?

这是我的输入文件

这个暗部是我需要识别的轮廓。

请与我分享您的经验。

【问题讨论】:

  • 您能提供更多信息吗?填充轮廓的检测标准是什么?

标签: image-processing opencv javacv


【解决方案1】:

对 JavaCV 不是很满意,所以这是我在 OpenCV 和 C(古老的东西)中解决这个问题的方法:

  1. 使用cvFindContours()查找图像中的所有轮廓
  2. 在这些轮廓上运行两个循环(迭代指针h_next 或JavaCV 中的任何内容)。对于外循环中的每个轮廓,将其与基于 检测到的每个其他轮廓匹配。 . .
  3. 计算每个轮廓的边界框。这将是一个CvRect 结构。
  4. 将两个 CvRects 传递给计算两个矩形之间的相交(重叠)面积的函数。
  5. 如果这个面积等于两个矩形中较小一个的面积,则较小矩形对应的轮廓被较大的矩形完全包围。

    这是查找交叉区域的代码。它一定是在网上某处漂浮。

    CvRect intersect(CvRect r1, CvRect r2) { CvRect intersection;

    // find overlapping region
    intersection.x = (r1.x < r2.x) ? r2.x : r1.x;
    intersection.y = (r1.y < r2.y) ? r2.y : r1.y;
    intersection.width = (r1.x + r1.width < r2.x + r2.width) ?
        r1.x + r1.width : r2.x + r2.width;
    intersection.width -= intersection.x;
    intersection.height = (r1.y + r1.height < r2.y + r2.height) ?
        r1.y + r1.height : r2.y + r2.height;
    intersection.height -= intersection.y;    
    
    // check for non-overlapping regions
    if ((intersection.width <= 0) || (intersection.height <= 0)) {
        intersection = cvRect(0, 0, 0, 0);
    }
    
    return intersection;
    

    }

【讨论】:

    【解决方案2】:

    这是 Python 代码中的一种简单方法。 (But as I stated in my comment below, It is not an universal answer applicable everywhere, It is just to show finding contour inside a contour can be done. And if your images are different, then you have to come with some different constraints other than i mentioned below)

    你在找到 Contours 之后要做的是,检查每个轮廓的面积是否小于指定值(我给了 10000,只是一个猜测),如果不是,它是更大的轮廓,避免它。如果小于指定值,它可能是我们旁边的正方形或矩形。

    所以我们找到它的宽度和高度,并检查纵横比是否接近 1。如果是,它就是我们的正方形。

    import cv2
    import numpy as np
    
    img = cv2.imread('sofcnt.jpg')
    gray = cv2.imread('sofcnt.jpg',0)
    
    ret,thresh = cv2.threshold(gray,127,255,1)
    
    cont,hier = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
    
    for cnt in cont:
        approx = cv2.approxPolyDP(cnt,0.02*cv2.arcLength(cnt,True),True)
        if cv2.contourArea(cnt) < 10000:
            x,y,w,h = cv2.boundingRect(cnt)
            if w/float(h) < 2:
                cv2.drawContours(img,[cnt],0,255,-1)
    
    
    cv2.imshow('a',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    结果:

    【讨论】:

    • 为什么你认为在某些多边形内需要类似于正方形的图形?也许作者想找到一个包含一些 pologon 中心的图形?谢谢。
    • +1 - 是的,你是对的,那么他也必须说明这一点。我想他想看看如何识别轮廓中的任何轮廓,所以这是一种这样做的类型。这样他必须找到其他解决方案,当然这不是一个普遍的答案,只针对这个特定的问题。
    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 2012-07-10
    • 2021-09-07
    • 2019-03-15
    • 2019-12-24
    • 2022-01-23
    • 2016-09-25
    • 2012-07-08
    相关资源
    最近更新 更多