问题
I have a RGB Image, which I plot with matplotlib.pyplot.imshow and it works fine. But now I want to change the plot, that where the value of the picture is e.g 1, the color of the plot should change to white at all this positions.
Is there a way to do this?
回答1:
Assuming that your image is a single-channel image rather than a three-channel image, the required task can be performed by defining a palette that maps indices (e.g. gray level intensities or picture values) into colors:
import numpy as np
palette = np.array([[ 0, 0, 0], # black
[255, 0, 0], # red
[ 0, 255, 0], # green
[ 0, 0, 255], # blue
[255, 255, 255]]) # white
I = np.array([[ 0, 1, 2, 0], # 2 rows, 4 columns, 1 channel
[ 0, 3, 4, 0]])
Image conversion is efficiently accomplished through NumPy's broadcasting:
RGB = palette[I]
And this is how the transformed image looks like:
>>> RGB
array([[[ 0, 0, 0], # 2 rows, 4 columns, 3 channels
[255, 0, 0],
[ 0, 255, 0],
[ 0, 0, 0]],
[[ 0, 0, 0],
[ 0, 0, 255],
[255, 255, 255],
[ 0, 0, 0]]])
回答2:
I will answer the general question of how to set a particular value to a particular color regardless of the color map.
In the code below for illustration purposes I supposed that is the value -1 that you want to map white. You will be wanting to do something different for your code.
This technique uses a masked array
to set the parts where your data is equal to -1 (the value you wish to map) and then uses cmap.set_bad()
to assign the color white to this value.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
value = -1
data = np.arange(100).reshape((10, 10))
data[5, :] = -1 # Values to set -1
masked_array = np.ma.masked_where(data == value, data)
cmap = matplotlib.cm.spring # Can be any colormap that you want after the cm
cmap.set_bad(color='white')
plt.imshow(masked_array, cmap=cmap)
plt.show()
Hope it helps.
来源:https://stackoverflow.com/questions/37719304/python-imshow-set-certain-value-to-defined-color