Shan
Shan

Reputation: 19243

How to display objects in different random colors on a white background in matplotlib python?

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.

Upvotes: 4

Views: 4565

Answers (2)

Delestro
Delestro

Reputation: 571

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.

Upvotes: 3

fraxel
fraxel

Reputation: 35269

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:

enter image description here

Hope thats random enuff for ya!

Upvotes: 7

Related Questions