Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

image - python imshow, set certain value to defined color

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

enter image description here

Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...