Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save OpenCV image with contour

Tags:

python

cv2

I want to save image with contour

Here is my code:

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)

Thanks a lot.

like image 587
Yang Avatar asked Sep 04 '17 07:09

Yang


People also ask

How do you contour with OpenCV?

To draw the contours, cv. drawContours function is used. It can also be used to draw any shape provided you have its boundary points. Its first argument is source image, second argument is the contours which should be passed as a Python list, third argument is index of contours (useful when drawing individual contour.

How does OpenCV detect contour?

Use the findContours() function to detect the contours in the image. Draw Contours on the Original RGB Image.

What is contour in OpenCV Python?

Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition. For better accuracy, use binary images.


2 Answers

What you want to do is to create a mask that you draw the contours on to, then use that to snip out the rest of the picture, or vice-versa. For instance, 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)
like image 134
Ken Y-N Avatar answered Sep 28 '22 03:09

Ken Y-N


The easiest way to save the contour as image is taking out its ROI(region of image) and saving it using imwrite() as follows -

First use cv2.boundingRect to get the bounding rectangle for a set of points (i.e. contours):

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

You can then use NumPy indexing to get your ROI from the image:

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

And save the ROI to a new file:

cv2.imwrite("roi.png", roi)
like image 25
Devashish Prasad Avatar answered Sep 28 '22 02:09

Devashish Prasad