2017-04-17 154 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) 
    
相關問題