randomize_colors(im, keep_vals=[0])[source]

Takes a greyscale image and randomly shuffles the greyscale values, so that all voxels labeled X will be labelled Y, and all voxels labeled Y will be labeled Z, where X, Y, Z and so on are randomly selected from the values in the input image.

This function is useful for improving the visibility of images with neighboring regions that are only incrementally different from each other, such as that returned by scipy.ndimage.label.

  • im (array_like) – An ND image of greyscale values.

  • keep_vals (array_like) – Indicate which voxel values should NOT be altered. The default is [0] which is useful for leaving the background of the image untouched.


image – An image the same size and type as im but with the greyscale values reassigned. The unique values in both the input and output images will be identical.

Return type



If the greyscale values in the input image are not contiguous then the neither will they be in the output.


>>> import porespy as ps
>>> import scipy as sp
>>> sp.random.seed(0)
>>> im = sp.random.randint(low=0, high=5, size=[4, 4])
>>> print(im)
[[4 0 3 3]
 [3 1 3 2]
 [4 0 0 4]
 [2 1 0 1]]
>>> im_rand = ps.tools.randomize_colors(im)
>>> print(im_rand)
[[2 0 4 4]
 [4 1 4 3]
 [2 0 0 2]
 [3 1 0 1]]

As can be seen, the 2’s have become 3, 3’s have become 4, and 4’s have become 2. 1’s remained 1 by random accident. 0’s remain zeros by default, but this can be controlled using the keep_vals argument.