【问题标题】:problem with shared boundaries of contours in opencvopencv中轮廓共享边界的问题
【发布时间】:2022-08-05 14:28:37
【问题描述】:

我正在尝试获取图像中的最大面积对象。 我应用了 Blur Kernel 5x5,然后应用 Canny 算法来获得边缘。然后我使用了findContours 方法和最大值contourArea,但它返回了错误的对象。

基础图像:

精明的图像:

找到所有轮廓的图像:

最大面积对象:

如您所见,它必须返回左侧框,但返回右侧框。 我认为问题在于左右框共享一个共同的边缘,但似乎只属于左侧。

这是代码sn-p:

    img_rgb = cv.imread(img_path)
    gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
    # blur with a kernel size of 5x5
    blur = cv.GaussianBlur(gray, (5, 5), 0)
    canny = cv.Canny(blur, 50, 50)
    #saving canny image
    cv.imwrite(\"canny.png\", canny)
    _, thresh = cv.threshold(canny, 127, 255, 0)
    contours, _ = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
    for c in contours:
        cv.drawContours(img_rgb, [c], 0, (randrange(255), randrange(255), randrange(255)), 3)
    #saving image with contours
    cv.imwrite(\"contours.png\", img_rgb)
    max_area_contour = max(contours, key=cv.contourArea)
    x, y, w, h = cv.boundingRect(max_area_contour)
    cv.rectangle(img_rgb, (x, y), (x + w, y + h), (0, 255, 0), 3)
    #saving the image with the biggest contour
    cv.imwrite(\"max_contour.png\", img_rgb)
  • 什么是预期的输出?
  • 检测左边的盒子而不是右边的盒子

标签: python opencv computer-vision contour


【解决方案1】:

我将 max 的关键函数设置为边界矩形的正方形,然后它可以正常工作:

img_rgb = cv.imread(img_path)
img_rgb_init = img_rgb.copy()
gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
# blur with a kernel size of 5x5
blur = cv.GaussianBlur(gray, (5, 5), 0)
canny = cv.Canny(blur, 50, 50)
#saving canny image
# cv.imwrite("canny.png", canny)
_, thresh = cv.threshold(canny, 127, 255, 0)
contours, _ = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
for c in contours:
    cv.drawContours(img_rgb, [c], 0, (random.randrange(255), random.randrange(255), random.randrange(255)), 3)

#saving image with contours
# cv.imwrite("contours.png", img_rgb)
def bounding_rect_size(in_cnt):
    x, y, w, h =cv.boundingRect(in_cnt)
    return w*h

x, y, w, h = cv.boundingRect(max(contours,key=bounding_rect_size))
cv.rectangle(img_rgb_init, (x, y), (x + w, y + h), (0, 255, 0), 3)
cv.imshow("",img_rgb_init)
cv.waitKey()

它工作不正确的原因是最大矩形的轮廓看起来像火车铁路。从矩形线的一侧向一个方向,从另一侧向另一个方向(某处的线断了)。这就是为什么这个轮廓的面积很小。

【讨论】:

  • 你能分享一下输出吗?这将是完整的
  • 不幸的是,这个解决方案效果不佳
  • 对于此类任务,没有适用于所有情况的解决方案。
  • 我知道,我并不声称它必须每次都有效,但是这个解决方案只适用于这个特定的图像,它是非常没用的
猜你喜欢
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 2020-06-17
相关资源
最近更新 更多