有没有好的色彩映射使用python的PIL将灰度图像转换为彩色图像?

Ada*_*dam 9 python colors matplotlib python-imaging-library

Matplotlib有很多很好的色彩图,但性能不好.我正在编写一些代码来使灰度图像变得鲜艳,其中使用颜色图进行插值是一个好主意.我想知道是否有开源彩色地图或演示代码使用Pillow通过colormap将灰度图像转换为彩色图像?


澄清:

  1. Matplotlib非常适合演示使用,但对于图像的thounsands表现不佳.
  2. Matplotlib色彩贴图
  3. 您可以将灰度图像映射到色彩图以获得彩色图像.

演示:

第一个图像是灰度,第二个图像是'jet'cmap,第三个是'热'.

Matplotlib演示

问题是我对颜色知之甚少,我想在PIL中实现这样的效果以获得更好的性能.

Phi*_*p F 9

您可以使用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')
Run Code Online (Sandbox Code Playgroud)

注意:

  • 如果输入图像为浮动图像,则值应在interval中[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)
    
    Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 8

我想通过@ImportanceOfBeingErnest提到的重复答案(如何将Numpy数组转换为应用matplotlib色彩映射的PIL图像)

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)
Run Code Online (Sandbox Code Playgroud)

表现结果如下:

PIL: 1.7473899199976586
PLT: 10.632971412000188
Run Code Online (Sandbox Code Playgroud)

他们都给我类似的hot彩色地图结果.

用热CMap测试图像