Issue
I have two contours in the first image. I need to segment out individual contours and make two images out of it like this: image1 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)
Solution
You are using the cv2.drawContours in wrong way. Passing the -1 as contour index would draw all the contours and not the individual ones. To draw the individual contours you need to pass the corresponding index as:
_, cnt, hierarchy = cv2.findContours(canvas.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for i in xrange(len(cnt)):
output_canvas = np.zeros(canvas.shape, dtype=np.uint8)
cv2.drawContours(output_canvas, cnt, i, np.array([255, 255, 255, 255]), -1)
cv2.imwrite("./contour{}.png".format(i), output_canvas)
Answered By - ZdaR Answer Checked By - Katrina (sql.easybugfix Volunteer)
Post a Comment
Post a Comment