To segment and detect figures in an image, the main idea is as follows:
- Convert image into grayscale using
cv2.cvtColor()
- Blur image with
cv2.GaussianBlur()
- Find edges with
cv2.Canny()
- Find contours with
cv2.findContours()
and sort from left-to-right using
imutils.contours.sort_contours()
to ensure that when we iterate through contours, they are in the correct order
- Iterate through each contour
- Obtain bounding rectangle using
cv2.boundingRect()
- Find ROI of each contour with Numpy slicing
- Draw bounding box rectangle using
cv2.rectangle()
Canny Edge Detection

Detected Contours

Cropped and saved ROIs

Output
Contours Detected: 2
Code
import numpy as np
import cv2
from imutils import contours
# Load image, grayscale, Gaussian blur, Canny edge detection
image = cv2.imread("1.png")
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3,3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)
# Find contours and extract ROI
ROI_number = 0
cnts = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts, _ = contours.sort_contours(cnts, method="left-to-right")
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
ROI = original[y:y+h, x:x+w]
cv2.rectangle(image, (x,y), (x+w,y+h),(36, 255, 12), 3)
cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
ROI_number += 1
print('Contours Detected: {}'.format(ROI_number))
cv2.imshow("image", image)
cv2.imshow("canny", canny)
cv2.waitKey()