Skip to content

Instantly share code, notes, and snippets.

@zactodd
Created November 29, 2020 11:42
Show Gist options
  • Save zactodd/4cfc68c50f822ab7ef7df5879a13bb61 to your computer and use it in GitHub Desktop.
Save zactodd/4cfc68c50f822ab7ef7df5879a13bb61 to your computer and use it in GitHub Desktop.
Function for partitioning image into sub images
import numpy as np
from itertools import accumulate, repeat, product
def partitions_with_overlap(image, partition_sizes, partitions_per_dim):
"""
Partition an image with overlap to list of images.
:param image: The image to partition.
:param partition_sizes: The sizes of the partition in each dimension.
:param partitions_per_dim: The number of partition per dimension.
:return: A list of images.
"""
shape = image.shape
assert len(shape) == len(partition_sizes) == len(partitions_per_dim)
dim_parts = []
for s, p, n in zip(shape, partition_sizes, partitions_per_dim):
strides = [(0, p)]
if n > 1:
overlap_diff = p - (p * n - s) / (n - 1)
strides.extend([(a, a + p) for a in accumulate(repeat(overlap_diff, n - 1))])
dim_parts.append(strides)
return [image[[np.s_[round(d0):round(d1)] for d0, d1 in dim_splits]] for dim_splits in product(*dim_parts)]
@zactodd
Copy link
Author

zactodd commented Dec 22, 2020

example

partitions_with_overlap(image, (1024, 1024, 3), (4, 5, 1))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment