[英]How to save OpenCV image with contour
我想用輪廓保存圖像
這是我的代碼:
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)
非常感謝。
您要做的是創建一個蒙版,在其上繪制輪廓,然后用它剪掉圖片的其余部分,反之亦然。 例如, 基於本教程:
(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)
將輪廓保存為圖像的最簡單方法是取出其 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)
我嘗試了很多次,最后,我可以做到:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.