I wish to write a python code that accepts a PIL image and split the image into M rows and N columns, such that one of the split region completely contains a patch of height H and width W starting at point (p,q).
I am mostly able to write the code and my attempt is shown below, but not able to generalise for any M and N. For example it sometimes breaks down for M=3, N=1.
Can someone help me out on this by either suggesting what change to make in the below code or any other way using PIL or Numpy.
from PIL import Image
def split_image_with_path(image, M, N, H, W, p, q):
"""
Splits a PIL image into M rows and N columns, ensuring one split region contains a path of height H and width W starting at point (p,q).
Args:
image: A PIL Image object.
M: Number of rows to split the image into.
N: Number of columns to split the image into.
H: Height of the patch.
W: Width of the patch.
p: Starting x-coordinate of the path.
q: Starting y-coordinate of the path.
Returns:
A list of PIL Image objects, representing the split image regions such that one of the split region contains the specified patch
"""
width, height = image.size
# Calculate the size of each split region.
split_width = width // N
split_height = height // M
# Ensure the path is completely contained within one split region.
if not (p < split_width * N and q < split_height * M and p + W <= split_width * N and q + H <= split_height * M):
raise ValueError("Path is not completely contained within one split region.")
# Split the image into M rows and N columns.
split_images = []
for i in range(M):
for j in range(N):
left = j * split_width
right = (j + 1) * split_width
top = i * split_height
bottom = (i + 1) * split_height
split_images.append(image.crop((left, top, right, bottom)))
return split_images
dummy_image = Image.open("/path/to/image.jpg")
display(dummy_image)
splits = split_image_with_path(dummy_image, M=3, N=1, H=100, W=100, p=10, q=10)
for split in splits:
display(split)