【问题标题】:How to get contours as image with opencv如何使用opencv获取轮廓作为图像
【发布时间】:2020-08-09 23:06:22
【问题描述】:

我想从图像中获取轮廓并仅在黑色图像上显示填充轮廓。

我的代码:

import cv2
import matplotlib.pyplot as plt
import numpy as np

img = cv2.imread('sample.jpeg')
black_img = np.zeros(img.shape)
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,tresh = cv2.threshold(imgray,127,255,0)
contours,hierarchy = cv2.findContours(tresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cv2.drawContours(black_img,contours,-1,(0,255,0),3)
plt.imshow(black_img)
plt.show()

这是sample.jpeg

没有给我预期的输出,而是黑色的 img。

我该怎么做?

【问题讨论】:

  • 我通常讨厌只发布链接,但这个有你的答案。为了最充分地回答您的问题,只需复制意大利面即可。 PyDoc

标签: python python-3.x numpy opencv


【解决方案1】:

我认为你想在 Python/OpenCV 中做的可能是:

输入:

import cv2
import numpy as np

img = cv2.imread('sample.jpeg')
black_img = np.zeros(img.shape)
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
thresh = 255 - thresh
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
cv2.drawContours(black_img,[contours[0]],0,(0,255,0),-1)
cv2.imwrite('sample_contour.jpg',black_img)
cv2.imshow('result',black_img)
cv2.waitKey(0)

结果:

【讨论】:

    【解决方案2】:

    一些问题

    cv2.drawContours(img2,contours,-1,(0,255,0),3)
    plt.imshow(black_img)
    

    首先,img2 来自哪里?我希望它会爆炸,但这不是您当时展示的图像。您可以改为在img 的顶部绘制,然后显示它。或者您可以尝试在black_img 上绘制轮廓。

    【讨论】:

    • img2 表示 black_img 对不起
    • 别抱歉。这就是编程,它在一定程度上是一个学习一个人容易犯什么错误的过程,以便将来可以防范。
    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 2011-06-13
    • 2013-04-02
    • 2023-03-31
    • 2015-03-02
    • 2015-04-24
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多