Reputation: 3070
I have a 3D image with a size of 128x128x64
that has 64
images, each image has the size of 128x128. The image presents three classes with the label is 0-background, 1-first object,2-second object. I am using matplotlib
to show the image.
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(32,32))
ax1 = plt.add_subplot(111)
ax1.imshow(image[:, :, 32])
I want to display it in color map. In which, the background should be black color, the object 1 will be the red color, and the object 2 will be the green color. How should I modify the code? Thanks The expected result likes the bottom left of the figure
Upvotes: 0
Views: 407
Reputation: 40667
Your question is not very clear. You say you want to obtain a result like the bottom left panel of the figure, but this image has shading and various levels of green and red.
From your question, I understood you have a 128x128 array with only 3 possible values: 0.
(background), 1.
(first object) and 2.
(second object). Is that correct? If so, in essence your question boils down to how to create a discret colormap with 3 levels and the colors black, red, green.
Here is what I would do:
# Generate some fake data for testing
img = np.zeros((128,128)) # Background
img[:50,:50] = np.ones((50,50)) # Object 1
img[-50:,-50:] = np.ones((50,50))*2 # Object 2
#>img
#>array([[ 1., 1., 1., ..., 0., 0., 0.],
# [ 1., 1., 1., ..., 0., 0., 0.],
# [ 1., 1., 1., ..., 0., 0., 0.],
# ...,
# [ 0., 0., 0., ..., 2., 2., 2.],
# [ 0., 0., 0., ..., 2., 2., 2.],
# [ 0., 0., 0., ..., 2., 2., 2.]])
# Create a custom discret colormap
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list("3colors", ['k','r','g'], N=3)
# Plot
# Don't forget to includes the bounds of your data (vmin/vmax)
# to scale the colormap accordingly
fig,ax = plt.subplots()
im = ax.imshow(img, cmap=cmap, vmin=0, vmax=2)
ax.grid(False)
cax = fig.colorbar(im)
cax.set_ticks([0,1,2])
Upvotes: 2