prog
prog

Reputation: 1073

split the each contour seperately

I am trying to split image based on the number of contours formed. The below image i get 2 rectangular boxes, how to split this seperately. Please help.

sample_Contours.jpg

Current Output:

Cuurent Output

Expected output:

Output1

Output2

Current output Code:

import cv2
image = cv2.imread('C:/sample_Contours.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] 
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20,1))
detect_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(thresh, [c], -1, (255,255,255), thickness=15) 
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,15))
detect_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(thresh, [c], -1, (255,255,255), thickness=15)
cv2.imshow('thresh',thresh)
cv2.waitKey(0)

Upvotes: 1

Views: 103

Answers (1)

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3333

You can use cv function boundingRect to find the rectangle that contains the countour. Then from this rectangle it is a simple cropping.

Try something like:

m = 32 #crop margin
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    crop = thresh[y-m:y+m+h,x-m:x+w+m]

Upvotes: 1

Related Questions