Skip to content Skip to sidebar Skip to footer

Splitting Very Large Images Into Overlapping Boxes/blocks/tiles/sections, Python, Opencv

I have very large images 10k by 10k that i need to split into overlapping boxes as shown below. Id like the box to be of size X by Y and I need to stride(distance the box moves acr

Solution 1:

Here is function, that splits image with overlapping from all sides. On the borders it will be filled with zeros.

What it essentially does: it creates a bigger image with zero padding, and then extract patches of size window_size+2*margin with strides of window_size. (You may want to adjust it to your needs)

def split(img, window_size, margin):

    sh = list(img.shape)
    sh[0], sh[1] = sh[0] + margin * 2, sh[1] + margin * 2
    img_ = np.zeros(shape=sh)
    img_[margin:-margin, margin:-margin] = imgstride=window_sizestep= window_size + 2 * margin

    nrows, ncols = img.shape[0] // window_size, img.shape[1] // window_size
    splitted = []
    for i in range(nrows):
        for j in range(ncols):
            h_start = j*stridev_start= i*stridecropped= img_[v_start:v_start+step, h_start:h_start+step]
            splitted.append(cropped)
    return splitted

Running this

img = np.arange(16).reshape(4,4)
out = split(img, window_size=2, margin=1)

will return

[array([[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  1.,  2.],
        [ 0.,  4.,  5.,  6.],
        [ 0.,  8.,  9., 10.]]),
 array([[ 0.,  0.,  0.,  0.],
        [ 1.,  2.,  3.,  0.],
        [ 5.,  6.,  7.,  0.],
        [ 9., 10., 11.,  0.]]),
 array([[ 0.,  4.,  5.,  6.],
        [ 0.,  8.,  9., 10.],
        [ 0., 12., 13., 14.],
        [ 0.,  0.,  0.,  0.]]),
 array([[ 5.,  6.,  7.,  0.],
        [ 9., 10., 11.,  0.],
        [13., 14., 15.,  0.],
        [ 0.,  0.,  0.,  0.]])]

Post a Comment for "Splitting Very Large Images Into Overlapping Boxes/blocks/tiles/sections, Python, Opencv"