2017-09-04 24 views
0

要保存圖像與輪廓我如何保存OpenCV的圖像與輪廓

這裏是我的代碼:

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) 

非常感謝。

+0

你試過[本教程中的建議(http://docs.opencv.org/3.2.0/d4/d73/tutorial_py_contours_begin.html)? –

+0

嗨,Ken, 是的,我試圖繪製輪廓,但我想用輪廓保存圖像。 – Yang

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