Draw bounding box around contours – skimage

The basic idea is to find the Xmin, Xmax, Ymin, Ymax of each identified coordinates of the contour and then create a rectangle using it. Lets understand this with an example:

Import the necessary libraries, read the input file, convert it to grayscale and plot it.

from skimage.measure import find_contours
from skimage.io import imread
import matplotlib.pyplot as plt
from skimage.color import rgb2gray

orig_img = imread('resources/stars.jpg')
gray_img = rgb2gray(orig_img)
plt.imshow(gray_img,interpolation='nearest', cmap=plt.cm.gray)

Now we use the skimage find_contours method to identify the contours in my input image

contours = find_contours(gray_img, 0.8)

fig, ax = plt.subplots()
ax.imshow(gray_img, interpolation='nearest', cmap=plt.cm.gray)

for n, contour in enumerate(contours):
    ax.plot(contours[n][:, 1], contours[n][:, 0], linewidth=2)

plt.show()

The contours in the image are groups x,y coordinates from which we need to find Xmin, Xmax, Ymin, Ymax which can be used to draw the bounding box.

import numpy as np
from skimage.draw import polygon_perimeter

bounding_boxes = []

for contour in contours:
    Xmin = np.min(contour[:,0])
    Xmax = np.max(contour[:,0])
    Ymin = np.min(contour[:,1])
    Ymax = np.max(contour[:,1])
    
    bounding_boxes.append([Xmin, Xmax, Ymin, Ymax])


with_boxes  = np.copy(gray_img)

for box in bounding_boxes:
    #[Xmin, Xmax, Ymin, Ymax]
    r = [box[0],box[1],box[1],box[0], box[0]]
    c = [box[3],box[3],box[2],box[2], box[3]]
    rr, cc = polygon_perimeter(r, c, with_boxes.shape)
    with_boxes[rr, cc] = 1 #set color white

plt.imshow(with_boxes, interpolation='nearest', cmap=plt.cm.gray)
plt.show()


That’s all! You can find the full notebook here.