如何用轮廓保存OpenCV图像

时间:2017-09-04 07:07:18

标签: python cv2

我想保存带轮廓的图像

这是我的代码:

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)

非常感谢。

3 个答案:

答案 0 :(得分:1)

你想要做的是创建一个用于绘制轮廓的面具,然后用它来剪掉图片的其余部分,反之亦然。例如,based on this tutorial

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

答案 1 :(得分:0)

将轮廓保存为图像的最简单方法是取出其ROI(图像区域),然后使用imwrite()进行保存,如下所示-

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

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

然后您可以使用NumPy索引从图像中获取投资回报率:

roi = img[y:y+height, x:x+width]

并将ROI保存到新文件:

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

答案 2 :(得分: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()