我想出了@ImportanceOfBeingErnest(
How to convert Numpy array to PIL image applying matplotlib colormap)提到的重复答案
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import timeit
from PIL import Image
def pil_test():
cm_hot = mpl.cm.get_cmap('hot')
img_src = Image.open('test.jpg').convert('L')
img_src.thumbnail((512,512))
im = np.array(img_src)
im = cm_hot(im)
im = np.uint8(im * 255)
im = Image.fromarray(im)
im.save('test_hot.jpg')
def rgb2gray(rgb):
return np.dot(rgb[:,:,:3], [0.299, 0.587, 0.114])
def plt_test():
img_src = mpimg.imread('test.jpg')
im = rgb2gray(img_src)
f = plt.figure(figsize=(4, 4), dpi=128)
plt.axis('off')
plt.imshow(im, cmap='hot')
plt.savefig('test2_hot.jpg', dpi=f.dpi)
plt.close()
t = timeit.timeit(pil_test, number=30)
print('PIL: %s' % t)
t = timeit.timeit(plt_test, number=30)
print('PLT: %s' % t)
表现结果如下:
PIL: 1.7473899199976586
PLT: 10.632971412000188
他们都给我类似的结果与热色地图.