Welcome to Ready Tensorβs image processing mini-project! In this guide, we demonstrate how to split an image into smaller tiles using Python and OpenCV.
The goal is to split a given image into smaller segments based on a specified number of rows and columns and save each segment as an individual image. This is commonly used in:
Install the required Python libraries using pip:
pip install numpy opencv-python
cv2 to read the image and os to handle file system operations.import numpy as np
import cv2
import os
image_path = "assignment-2.jpg"
image = cv2.imread(image_path)
if image is None:
print("Error: Could not load image. Check the file path.")
exit()
num_rows = 6
num_cols = 3
image_height, image_width, _ = image.shape
sub_image_height = image_height // num_rows
sub_image_width = image_width // num_cols
output_dir = "output_bars"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for row in range(num_rows):
for col in range(num_cols):
start_x = col * sub_image_width
start_y = row * sub_image_height
end_x = (col + 1) * sub_image_width
end_y = (row + 1) * sub_image_height
sub_image = image[start_y:end_y, start_x:end_x]
output_path = os.path.join(output_dir, f"piece_{row}_{col}.jpg")
cv2.imwrite(output_path, sub_image)
print(f"Saved: {output_path}")
print("Image successfully split into pieces!")
output_bars/
βββ piece_0_0.jpg
βββ piece_0_1.jpg
βββ piece_0_2.jpg
βββ ...
βββ piece_5_2.jpg
Tips:
.png instead of .jpg.Tkinter or deploy it as a Flask web app.