2017-04-17 170 views
2

Matplotlib有很多很好的彩色贴图,但性能很差。我正在编写一些代码来使灰度图像变得丰富多彩,其中插入颜色图是一个好主意。我想知道是否有可用的开源彩色地图或演示代码使用Pillow通过颜色映射将灰度图像转换为彩色图像?是否有任何好的彩色地图使用python的PIL将灰度图像转换为彩色图像?


澄清:

  1. Matplotlib是良好的演示使用,但糟糕的服务表现为图像的thounsands。
  2. Matplotlib colormaps
  3. 您可以将灰度图像映射到colormap以获得丰富多彩的图像。

演示:

第一图像是灰度,第二被映射在 '射流' CMAP,第三个是 '热'。

Matplotlib demo

的问题是,我不知道很多关于颜色,我想达到更好的性能在PIL这样的效果。

+0

请澄清你的问题。“但在性能不好”,为什么这样做不好的表现呢? “插入彩色地图是一个好主意”,你是什么意思? “将灰度图像转换成彩色图像”,以什么方式?应该将哪种颜色映射到哪种灰色调?你有没有输入图像的例子,结果应该是什么? – Bart

+0

[如何将Numpy数组转换为应用matplotlib颜色映射的PIL图像]的可能重复(http://stackoverflow.com/questions/10965417/how-to-convert-numpy-array-to-pil-image-applying-matplotlib-颜色表) – ImportanceOfBeingErnest

回答

3

我想通了与@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 

他们俩给我hot彩色地图类似的结果。

Test Image with hot CMap

1

您可以从matplotlib使用彩色地图,并将其应用没有任何matplotlib数字等 这将会使事情更快:

import matplotlib.pyplot as plt 

# Get the color map by name: 
cm = plt.get_cmap('gist_rainbow') 

# Apply the colormap like a function to any array: 
colored_image = cm(image) 

# Obtain a 4-channel image (R,G,B,A) in float [0, 1] 
# But we want to convert to RGB in uint8 and save it: 
Image.fromarray((colored_image[:, :, :3] * 255).astype(np.uint8)).save('test.png') 

注:

  • 如果您的输入图像是浮动的,则值应该在[0.0, 1.0]的区间内。
  • 如果输入图像是整数,则整数应该在[0, N)的范围内,其中N是地图中的颜色数。但是你可以根据你的地图重新取样到任意数量的值的需要:

    # If you need 8 color steps for an integer image with values from 0 to 7: 
    cm = plt.get_cmap('gist_rainbow', lut=8) 
    
相关问题