我想从图像中获取轮廓,并仅在黑色图像上显示填充的轮廓。
我的代码:
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。
我怎样才能做到这一点?
最佳答案
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)
结果:
关于python - 如何使用opencv将轮廓作为图像获取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63332191/