Here's a Python script that splits a long vertical image into chunks with a specified width and overlapping:
from PIL import Image
import os
def split_image(input_path, output_dir, chunk_width=768, overlap=100):
"""
Split a vertical image into chunks with specified width and overlap.
:param input_path: Path to the input image
:param output_dir: Directory to save the chunks
:param chunk_width: Width of each chunk (default 768)
:param overlap: Pixel overlap between chunks (default 100)
"""
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Open the image
with Image.open(input_path) as img:
# Get image dimensions
img_width, img_height = img.size
# Ensure chunk width doesn't exceed image width
chunk_width = min(chunk_width, img_width)
# Calculate chunk positions
current_y = 0
chunk_number = 0
while current_y < img_height:
# Calculate the height of the current chunk
chunk_height = min(chunk_width, img_height - current_y)
# Crop the chunk
chunk = img.crop((0, current_y, chunk_width, current_y + chunk_height))
# Save the chunk
output_filename = os.path.join(output_dir, f"chunk_{chunk_number:04d}.png")
chunk.save(output_filename)
# Move to next chunk position
current_y += chunk_width - overlap
chunk_number += 1
print(f"Split {input_path} into {chunk_number} chunks")
def main():
# Example usage
input_image = "long_vertical_image.png" # Replace with your image path
output_directory = "image_chunks"
# Split image with default settings
split_image(input_image, output_directory)
# Optional: Custom chunk width and overlap
# split_image(input_image, output_directory, chunk_width=1024, overlap=200)
if __name__ == "__main__":
main()
This script does the following:
- Uses Pillow (PIL) to handle image processing
- Creates a function
split_image() that:
- Takes an input image path
- Creates an output directory
- Splits the image into chunks of specified width
- Adds overlap between chunks
- Saves chunks as separate image files
Key features:
- Handles images of different sizes
- Allows customization of chunk width and overlap
- Automatically names chunks sequentially
- Creates output directory if it doesn't exist
Requirements:
pip install Pillow
Usage:
- Replace
"long_vertical_image.png" with your image path
- Run the script
- Chunks will be saved in the
image_chunks directory
Customization options:
- Change
chunk_width to adjust chunk size
- Change
overlap to control chunk overlap
Example variations:
# Split with custom width and more overlap
split_image(input_image, output_directory, chunk_width=1024, overlap=200)
The script ensures that:
- Chunks don't exceed image dimensions
- Overlap is maintained between chunks
- Chunks are saved with sequential names