【问题标题】:Python opencv: Draw lines between points and find full contoursPython opencv:在点之间画线并找到完整的轮廓
【发布时间】:2021-06-29 13:43:17
【问题描述】:

我有一组三个点,在一个三角形中。例如:[[390 37]、[371 179]、[555 179]]

画完线,How to draw lines between points in OpenCV?

如何找到我刚刚绘制的线条之间的完整轮廓?

我不断收到以下错误:

    img = np.zeros([1000, 1000, 3], np.uint8)
    cv2.drawContours(img, triangle_vertices, 0, (0, 0, 0), -1)
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

错误:(-210:不支持的格式或格式组合)[开始]FindContours 仅在模式 != CV_RETR_FLOODFILL 时支持 CV_8UC1 图像,否则仅在函数 'cvStartFindContours_Impl' 中支持 CV_32SC1 图像

【问题讨论】:

    标签: python python-3.x numpy opencv


    【解决方案1】:

    我相信您的主要问题是您只能在二值图像(而不是颜色)上找到轮廓。您的点还需要在 Numpy 数组中(作为 x,y 对——注意逗号)。这就是我在 Python/OpenCV 中的做法。

    import cv2
    import numpy as np
    
    # create black background image
    img = np.zeros((500, 1000), dtype=np.uint8)
    
    # define triangle points
    points = np.array( [[390,37], [371,179], [555,179]], dtype=np.int32 )
    
    # draw triangle polygon on copy of input
    triangle = img.copy()
    cv2.polylines(triangle, [points], True, 255, 1)
    
    # find the external contours
    cntrs = cv2.findContours(triangle, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
    
    # get the single contour of the triangle
    cntr = cntrs[0]
    
    # draw filled contour on copy of input
    triangle_filled = img.copy()
    cv2.drawContours(triangle_filled, [cntr], 0, 255, -1)
    
    # save results
    cv2.imwrite('triangle.jpg', triangle)
    cv2.imwrite('triangle_filled.jpg', triangle_filled)
    
    cv2.imshow('triangle', triangle)
    cv2.imshow('triangle_filled', triangle_filled)
    cv2.waitKey()
    

    三角形多边形图像:

    三角形填充轮廓图像:

    【讨论】:

    • 谢谢,顺便说一句,这条线在做什么? cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1],为什么会有第二个轮廓,它应该总是 [0] 吗?只是好奇
    • 该行用于确定从 findContours 返回了多少东西,并且只获取轮廓而不是层次结构。除了 2 个项目(层次结构和轮廓)之外,不同版本的 findContours 返回。这里的[0]指的是哪个返回项,而不是第一个轮廓。 cntrs 指的是所有返回项目,包括层次结构和轮廓。 3.4.2 附近的版本返回 3 个项目:图像、层次结构和轮廓,而不仅仅是层次结构和轮廓,就像在大多数版本中一样。见docs.opencv.org/3.4.2/d3/dc0/…
    • 好的,最后一个问题,drawContours 和折线有什么区别?他们似乎在做同样的事情,谢谢
    • 视觉上没有多少。但是轮廓可以有许多顶点(与线条中的像素一样多),具体取决于直线度和轮廓的绘制方式。等高线还具有与其关联的层次结构,而折线则没有。此外,如果您有图像,则可以找到轮廓,但无法直接找到折线的顶点。但是您可以从轮廓中获取顶点,并经常将它们减少为几个简单形状的顶点。
    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2014-04-09
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多