Home > Software design >  Convert cmap values to RGB for PIL.Image
Convert cmap values to RGB for PIL.Image

Time:10-19

I want to use PIL.Image to save a figure and I want to use matplotlib cmaps to map the data to a color. I have tried the following:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from PIL import Image

M, N = 255, 255
data = np.arange(M*N).reshape((M, N))

cmap_name = 'autumn_r'
cmap_name = cmap_name
cmap = plt.get_cmap(cmap_name)
norm = mpl.colors.Normalize()
scalarMap = cm.ScalarMappable(norm=norm, cmap=cmap)

plt.imshow(data, cmap=cmap)
plt.show()

colors = scalarMap.to_rgba(data)

image = Image.fromarray((colors[:, :, :3]*256).astype(np.uint8))
image.show()

Which plots this in matplotlib:

matplotlib

However, it plots this in the Image:

PIL.Image

How can I get PIL.Image to show the same colors as matplotlib?

If its possible to also add the alpha channel, that will be useful

CodePudding user response:

You need to give PIL the same normalisation and cmap you give matplotlib, so it can do the same mapping from 2D array -> normalised -> mapped to cmap.

I rewrote your sample code to be a bit simpler:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from PIL import Image

M, N = 255, 255
data = np.arange(M*N).reshape((M, N))
cmap = cm.autumn_r
plt.imshow(data, cmap=cmap)

norm = mpl.colors.Normalize()

Then your answer is:

Image.fromarray(np.uint8(cmap(norm(data))*255)).show()

(Found the solution here, might be a dupe.)

  • Related