PIL/pillow image output is redder than the desired RGB values

人盡茶涼 提交于 2019-12-11 20:18:43

问题


I've been trying to generate the equivalent of matplotlib's matshow function as a PIL image. During this process, I realized that the colors that I'm generating by applying the colormaps are always slightly redder than they are in the mathshow version.

Here is a quick test code that I wrote up to test and verify the scenario:

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

data = np.ones((5,5))*0.5
cmap = matplotlib.cm.jet

#generate PIL image
m = matplotlib.cm.ScalarMappable(norm=None, cmap=cmap)
colormapped = m.to_rgba(data)*255
print(colormapped)
outputImage = Image.fromarray(np.uint8(colormapped))
outputImage.show()
print(list(outputImage.getdata()))

#generate matplotlib figure
fig = plt.figure()
ax = fig.add_axes((0,0,1,1))
ax.set_axis_off()
ax.matshow(data, cmap=cmap)
plt.show()

The data, a 5x5 matrix filled with 0.5, should result in an image that is purely blue according to the jet colormap.

When I print out the matrix generated by the to_rgba() function and also by the Image.getdata() function, I get the desired value of (0,0,127.5). However, when I show the image (or save it as a .png), the PIL version is "redder" than the matshow version - the matshow version has the desired value of (0,0,127), while the PIL version has a value of (31,0,111), according to MS Paint (and verified on Photoshop).

I'm presuming that this has to do with the way PIL/pillow is rendering the image. However, how do I fix this? I need by blues to stay blue! (the green channel is also affected, but nowhere near as much - for example, (136, 136, 136) becomes (145, 134, 116))

I'm doing this on Python 3.4.1 under Anaconda 2.0.1 on Win8 x64. Below are the package versions that I'm using: numpy: 1.9.1 pillow: 2.5.1 matplotlib: 1.4.2


回答1:


Without the "outputImage.show()" for PIL, the image seems to be rendered properly when saving as a PNG. The visual output is incorrect, and when saving after the visual output has been displayed, the saved image reflects what was rendered by the original output.

Furthermore, I could only reproduce this issue on my Win8 machine under Python 3.4.1 with PIL 2.5.1. On Python 2.7.9 in Win8 with PIL 1.1.7, the displayed image failed to render when using the show() command (it keeps saying that the file is missing) and the saved image is correctly colored.



来源:https://stackoverflow.com/questions/27676326/pil-pillow-image-output-is-redder-than-the-desired-rgb-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!