I have an image where i have objects labeled with numbers e.g all the pixels belong to object 1 has the value 1 and so on. Rest of the image is zero.
I want to see every object in different random colors with white background.
I have tried several color maps like gray,jet etc but none of them meet the requirement because they sequentially color the objects from dark to light.
Thanks a lot.
Make your own colormap with random colors is a quick way to solve this problem:
colors = [(1,1,1)] + [(random(),random(),random()) for i in xrange(255)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)
First color is white, to give you the white background.
Full code in action:
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
import matplotlib
from random import random
colors = [(1,1,1)] + [(random(),random(),random()) for i in xrange(255)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)
im = scipy.misc.imread('blobs.jpg',flatten=1)
blobs, number_of_blobs = ndimage.label(im)
plt.imshow(blobs, cmap=new_map)
plt.imsave('jj2.png',blobs, cmap=new_map)
plt.show()
Sample labelled, randomly colored output:
Hope thats random enuff for ya!
I came across this same question, but I wanted to use HSV colors.
Here is the adaptation needed:
note that on this case I know the number of labels (nlabels)
from matplotlib.colors import LinearSegmentedColormap
import colorsys
import numpy as np
#Create random HSV colors
randHSVcolors = [(np.random.rand(),1,1) for i in xrange(nlabels)]
# Convert HSV list to RGB
randRGBcolors=[]
for HSVcolor in randHSVcolors:
randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0],HSVcolor[1],HSVcolor[2]))
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
I'm not using the white for first color, but should be the same from the previous answer to implement it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With