JP1
JP1

Reputation: 733

Iterative patch generation for image segmentation - possible to optimise?

I am using CNN for voxel classification for segmentation of images. I am using a nested for loop to generate the patches used for the neural network but as the images I have are 3 dimensional, it's taking forever.

Is there anyway this can be optimised that I can't see?

def data_gen(image, labels, patch_size):

"""
:param image: 3 dimensional numpy matrix of image
:param labels: 3 dimensional numpy matrix of mask
:param patch_size: desried dimension of patch size
:return: array of patches and array of labels

"""

Patch_array = np.array([])
Label_array = np.array([])

PS = (patch_size - 1)/2

npad = ((PS, PS), (PS, PS), (PS,PS))

# Pad whole image with zeros to allow for patches at edges
image_pad = np.pad(image, pad_width=npad, mode='constant', constant_values = 0)

# Cycle over all voxels
for x in range(PS, image.shape[0]):
    for y in range(PS, image.shape[1]):
        for z in range(PS, image.shape[2]):

            # Add patch to array
            Patch_array = np.append(Patch_array, image_pad[x-PS:x+PS+1,y-PS:y+PS+1,z-PS:z+PS+1])

            Label_array = np.append(Label_array, labels[x,y,z])

return Label_array, Patch_array

Thanks!

Upvotes: 0

Views: 535

Answers (1)

jmetz
jmetz

Reputation: 12773

There's a Scikit-Image utility function for this:

http://scikit-image.org/docs/dev/api/skimage.util.html#view-as-windows

e.g.

from skimage.util.shape import view_as_windows
window_shape = (patch_size, patch_size, patch_size)
patch_array = view_as_windows(A, window_shape)

Under the hood, this uses as_strided from numpy.lib.stride_tricks.

Upvotes: 1

Related Questions