【问题标题】:How to draw contours using opencv in Python?如何在 Python 中使用 opencv 绘制轮廓?
【发布时间】:2018-02-23 13:16:22
【问题描述】:

我已预处理以下图像:

现在我想使用findContours 方法从图像中查找单元格,然后使用drawContours 为图像中的每个单元格绘制轮廓。我这样做了,但没有显示任何内容。

contours =  cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

我收到以下错误。

contours 不是 numpy 数组,也不是标量

其他答案对我没有帮助。

我也使用以下解决方案。

contours =  cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
ctr = numpy.array(contours).reshape((-1,1,2)).astype(numpy.int32)
cv2.drawContours(img, ctr, -1, (0, 255, 0), 3)

但是这个解决方案没有在给定的图像上绘制任何东西。

【问题讨论】:

    标签: python numpy opencv image-processing computer-vision


    【解决方案1】:

    更新,OpenCV 4.0 更改cv2.findContours。所以我修改了代码示例。还有一种更通用的方式:

    cnts, hiers  = cv2.findContours(...)[:-2]
    

    cv2.findContours 返回一个元组,而不仅仅是轮廓。你可以这样做:

    ## Find contours
    if cv2.__version__.startswith("3."):
        _, contours, _ = cv2.findContours(bimg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    else:
        contours, _ = cv2.findContours(bimg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    ## Draw contours 
    cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
    

    相关的类似问题:

    (1)Python Opencv drawContour error

    (2)How to use `cv2.findContours` in different OpenCV versions?

    【讨论】:

    • 谢谢!看来我使用的版本> 3。
    • @MihaiAlexandru-Ionut 注意,OpenCV 4.0 把cv2.findContours 改回来了,所以我修改了代码示例。
    【解决方案2】:

    cv2.findContours 返回的元组具有(im, contours, hierarchy) 的形式,其中im 是具有可视化轮廓的图像,contours(x_values, y_values)heirarchy 形式的两个numpy 数组的元组取决于检索模式。由于您使用的是 CV_RETR_EXTERNAL,heirarchy 没有太大意义。

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 2017-05-20
      • 2019-01-25
      • 2019-02-12
      • 1970-01-01
      • 2018-07-09
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多