问题
I'm having following problem: I have black/white images, which I have to colorize: Every white "blob" in the image represents an instance of an object and I want to color every object with a new color, but for every image i want to use the same color scheme:
For example:
- 1st image: 3 Objects -> used colors: red, green, yellow
- 2nd image: 2 Objects -> used colors: red, green
- 3rd image: 5 objects -> used colors: red, green, yellow, pink, orange
I've colored a couple of images by hand to show what the result should look like:
Black / white mask that has to be colorized
2 objects, 2 colors: green, yellow
4 objects, 4 colors: green, yellow, red, light grey
To do it automatically i've tried the approach here:
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()
Problem with that is, that if I run in on my images, the objects get colorized differently depending on how many objects there are in each image:
For example:
1st image: 3 Objects -> used colors: red, green, yellow
2nd image: 2 Objects -> used colors: orange, yellow
3rd image: 5 objects -> used colors: red, orange, green, limegreen, yellow
4th image: 3 objects -> used colors: red, green, yellow
Here are some pictures to visualize the incorrect coloring of the 3rd image:
2 objects, coloured orange and pink
Another image with 2 objects, coloured orange and pink
Image with 3 objects, now colors change: orange, yellow and green (what I need: orange, pink and new color
回答1:
Since you are generating a random colormap, it's no surprise the colors are not consistent.
You want to create one colormap with your colors of choice, and pass that colormap to each image, regardless of the number of blobs present. Note however, that by default the colormaps are normalized to the range of your data. Since the range of the data changes depending on the number of blobs found, you need to explicitly set the normalization using vmin=
and vmax
. Here is a demonstration using 4 different images:
import imageio
from scipy import ndimage
colors = ['black','red', 'green', 'yellow', 'pink', 'orange']
vmin = 0
vmax = len(colors)
cmap = matplotlib.colors.ListedColormap(colors)
fig, axs = plt.subplots(4,1, figsize=(3,3*4))
for file,ax in zip(['test1.png','test2.png','test3.png','test4.png'], axs):
im = imageio.imread(file)
blobs, number_of_blobs = ndimage.label(im)
ax.imshow(blobs, cmap=cmap, vmin=vmin, vmax=vmax)
来源:https://stackoverflow.com/questions/60783969/how-to-color-objects-in-an-image-with-different-color-each