Skip to content

Instantly share code, notes, and snippets.

@guumaster
Last active February 2, 2023 11:02
Show Gist options
  • Save guumaster/416cc93916e80f2d6c0dbdcc94e598a9 to your computer and use it in GitHub Desktop.
Save guumaster/416cc93916e80f2d6c0dbdcc94e598a9 to your computer and use it in GitHub Desktop.

Split an image into a grid

Simple script to split an image into smaller grid of equal sizes, eg: 2x2, 2x3, 4x4, etc.

Requirements

It uses OpenCV to read/write the images. so you need to first install it with:

pip install opencv-python

Usage

python split.py <source_image>  2x2 <output_dir>

ex:

python split.py colorful_background.png  2x2 ./output

this command will split and create 4 cell images into output folder.

import cv2
import argparse
def split_image(image, rows, cols):
height, width, _ = image.shape
cell_width = width // cols
cell_height = height // rows
cells = []
for row in range(rows):
for col in range(cols):
start_x = col * cell_width
start_y = row * cell_height
end_x = start_x + cell_width
end_y = start_y + cell_height
cell = image[start_y:end_y, start_x:end_x]
cells.append(cell)
return cells
def save_cells(cells, output_dir):
for i, cell in enumerate(cells):
cell_path = f"{output_dir}/cell_{i}.jpg"
cv2.imwrite(cell_path, cell)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Split an image into smaller images.")
parser.add_argument("image_path", help="Path to the image to be split.")
parser.add_argument("grid", help="Number of rows and columns in the form ROWSxCOLS (e.g. 2x3).")
parser.add_argument("output_dir", help="Directory to save the split images.", default=".")
args = parser.parse_args()
if None in [args.image_path, args.grid]:
parser.print_help()
else:
image = cv2.imread(args.image_path)
rows, cols = [int(x) for x in args.grid.split("x")]
cells = split_image(image, rows, cols)
save_cells(cells, args.output_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment