[英]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 eg all the pixels belong to object 1 has the value 1 and so on. 我有一幅图像,其中有一些标有数字的对象,例如,属于对象1的所有像素的值均为1,依此类推。 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. 我遇到了同样的问题,但是我想使用HSV颜色。
Here is the adaptation needed: 这是所需的改编:
note that on this case I know the number of labels (nlabels) 请注意,在这种情况下,我知道标签数(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. 我没有将白色用作第一色,但是应该与上一个答案中的相同以实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.