如何使用opencv获取轮廓作为图像

2024-09-27 07:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的代码:

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()

enter image description here

这是sample.jpeg

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

我该怎么做


Tags: sample图像importimgasnppltcv2
2条回答

我认为您希望在Python/OpenCV中执行的操作可能是:

输入:

enter image description here

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)

结果:

enter image description here

关于

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

首先img2来自哪里?我预计会爆炸,但这不是你当时展示的图像。您可以在img的顶部绘制,然后显示它。或者您可以尝试在black_img上绘制等高线

相关问题 更多 >

    热门问题