Ask Your Question
1

Segmenting two contours into two different images of same size using openCV-python

asked 2018-12-08 01:23:27 -0600

Esh gravatar image

updated 2020-09-15 11:23:12 -0600

I have two contours in the first image:input image .

I need to segment out individual contours and make two images out of it like this: Image 1

and

image2.

The individual output image has to be of the same dimension as the input image. How can this be achieved using openCV-python ? My code for drawing contours:

image, contours, hier = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
# convert all coordinates floating point values to int
box = np.int0(box)
# draw a red 'nghien' rectangle
cv2.drawContours(im, [box], 0, (0, 0, 255))
cv2.drawContours(im, contours, -1, (255, 255, 0), 1)
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2018-12-08 01:40:47 -0600

berak gravatar image

you could simply overwrite the unwanted contour(s), with cv2.FILLED to erase them

(untested) code:

# keep #0, erase #1
clone1 = im.copy()
cv2.drawContours(clone1, contours, 1, (0,0,0), cv2.FILLED) # paint it black
cv2.imwrite("contour_0.png", clone1)

# keep #1, erase #0
clone2 = im.copy()
cv2.drawContours(clone2, contours, 0, (0,0,0), cv2.FILLED) # paint it black
cv2.imwrite("contour_1.png", clone2)
edit flag offensive delete link more

Comments

Works. Thanks. I found that this works too when you have multiple contours:

_, cnt, hierarchy = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for i in range(len(cnt)):
    output_canvas = np.zeros(img.shape, dtype=np.uint8)
    cv2.drawContours(output_canvas, cnt, i, (255,255,255), -1)
    cv2.imwrite("./contour{}.jpg".format(i), img)
    cv2.imshow("image", img)
Esh gravatar imageEsh ( 2018-12-09 00:27:39 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-12-08 01:23:27 -0600

Seen: 1,667 times

Last updated: Dec 08 '18