You can download this code by clicking the button below.
This code is now available for download.
This function loads an image, converts it to a grayscale image, and uses Canny edge detection to find contours. Then, it finds the largest contour and calculates its bounding box. Finally, the function rotates the image around the center of the bounding box.
Technology Stack : scikit-image, numpy
Code Type : Image processing
Code Difficulty : Intermediate
import numpy as np
from skimage import feature, io, transform
def find_contours_and_rotate_image(input_image_path, angle):
# Load the image
image = io.imread(input_image_path)
# Convert the image to grayscale
gray_image = feature.canny(image)
# Find contours in the image
contours, _ = feature.find_contours(gray_image, 0.5)
# Calculate the bounding box for the largest contour
if contours:
largest_contour = max(contours, key=lambda c: np.sum(c[:, 1]))
bounding_box = transform.bbox(largest_contour)
else:
bounding_box = (0, 0, image.shape[1], image.shape[0])
# Rotate the image around the center of the bounding box
rotated_image = transform.rotate(image, angle, resize=False, mode='edge', center=bounding_box[:2])
return rotated_image