Andor
Andor

Reputation: 2037

Pyplot color maps showing different results

Playing a bit with some scikit-image code samples and pyplot I've found different results on my images depending on how I'm applying my color maps, and I don't know why.

When I apply a color map as a plugin when showing an image, everything goes OK, when I do it directly to the image, it goes totally black. I'm confused because I want to apply that color maps to images I want to save (instead of show) and I don't know how to do it properly.

import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2hed


ihc_rgb = data.immunohistochemistry()
ihc_hed = rgb2hed(ihc_rgb)

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
ax0, ax1, ax2, ax3 = axes.ravel()

ax0.imshow(ihc_hed[:, :, 0], cmap=plt.cm.gray)
ax0.set_title("plugin")

ax1.imshow(plt.cm.gray(ihc_hed[:, :, 0]))
ax1.set_title("direct")

[this goes on a bit]

enter image description here

Upvotes: 2

Views: 403

Answers (2)

hitzg
hitzg

Reputation: 12691

From the your comment on the Stefan van der Walt's answer I conclude that you dont want to save matplotlib figures, but images directly. As Stefan pointed out, you need to scale the values before you can use the colormap. Matplotlib provides the class Normalize for that:

import matplotlib.pyplot as plt
import matplotlib.colors
from skimage import data
from skimage.color import rgb2hed

ihc_rgb = data.immunohistochemistry()
ihc_hed = rgb2hed(ihc_rgb)

fig, axes = plt.subplots(1, 3, figsize=(8, 3))
ax0, ax1, ax2 = axes.ravel()

ax0.imshow(ihc_hed[:, :, 0], cmap=plt.cm.gray)
ax0.set_title("plugin")

ax1.imshow(plt.cm.gray(ihc_hed[:, :, 0]))
ax1.set_title("direct")

norm = matplotlib.colors.Normalize()
gray_image = plt.cm.gray(norm(ihc_hed[:,:,0])) 

ax2.imshow(gray_image)
ax2.set_title("direct with norm")

for a in axes:
    a.xaxis.set_visible(False)
    a.yaxis.set_visible(False)

plt.gcf().tight_layout()
plt.show()

enter image description here

Upvotes: 1

Stefan van der Walt
Stefan van der Walt

Reputation: 7253

The values inside ihc_hed[:, :, 0] lie between -1.37 and -0.99. The default behavior of imshow is to display the whole range of values. plt.cm.gray, on the other hand, operates on images with values between 0 and 1.

The automatic rescaling is saving you in the first case, but not the second. I recommend always using imshow with a fixed range: imshow(image, vmin=0, vmax=1, cmap='gray')

Upvotes: 3

Related Questions