如何使用轮廓保存OpenCV图像

6

我希望能够保存带轮廓的图片。

这是我的代码:

img = cv2.imread('123.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
image, contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    # some code in here
    cv2.imwrite('234.jpg', cnt)

非常感谢。

你尝试过这个教程中的建议吗? - Ken Y-N
嗨,Ken, 是的,我已经尝试绘制轮廓,但我想保存带有轮廓的图像。 - Yang
“保存带轮廓的图像”是什么意思? - Ken Y-N
嗨,肯恩,我的意思是我想丢弃轮廓外的图像部分,抱歉我的陈述不够明确。 - Yang
3个回答

8
你需要做的是创建一个蒙版,然后在上面绘制轮廓,最后使用它来剪切图片的其余部分,或者反过来。例如,基于这个教程
(contours, _) = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
mask = np.ones(img.shape[:2], dtype="uint8") * 255

# Draw the contours on the mask
cv2.drawContours(mask, contours, -1, 0, -1)

# remove the contours from the image and show the resulting images
img = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow("Mask", mask)
cv2.imshow("After", img)
cv2.waitKey(0)

如果您不介意的话,能否解释一下我们为什么要使用掩码? - l0n3_w01f

3

将轮廓另存为图像的最简单方法是使用其ROI(图像区域)并使用以下方式保存它:imwrite()。

首先,使用cv2.boundingRect获取一组点(即轮廓)的边界矩形:

x, y, width, height = cv2.boundingRect(contours[i])

您可以使用NumPy索引从图像中获取ROI:
roi = img[y:y+height, x:x+width]

将ROI保存到新文件中:

cv2.imwrite("roi.png", roi)

2
是的,如果形状是规则的形状,如正方形或矩形,甚至圆形在某种程度上也可以,那么这个解决方案是不错的。但是对于处理不规则形状模式来说,这不是一个好方法,因为额外的不需要的图像区域将被包括在ROI中。 - Zain Ul Abidin

0

我尝试了很多次,最终终于成功了:

image= cv2.imread('muroprueba.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
cnts, herarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image,cnts,-1,(0,255,0),1)

cv2.imshow('image1',image)
cv2.waitKey(0)
cv2.imwrite('F:\caso1.jpg',image)            #Save the image
cv2.destroyAllWindows()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接