python 灰度图像转彩色_是否有任何好的色彩映射表,可以使用python的PIL将灰度图像转换为彩色图像?...

本文探讨了如何使用Matplotlib和Pillow将灰度图像转换为彩色图像,并通过颜色映射实现这一目标。作者对比了两种方法的性能,发现Pillow在处理大量图像时表现更佳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Matplotlib has a lot of good color maps, but is bad in performance. I'm writing some code to make gray-scale image colorful where interpolate with color map is a good idea. I wonder whether there are open source color maps available or demo code to use Pillow to convert gray-scale images into colorful ones via colormap?

Clarify:

Matplotlib is good for demo use, but bad performace for thounsands of images.

You can map grayscale images to colormaps to get colorful ones.

Demo:

The first image is grayscale, second is mapped in 'jet' cmap, third being 'hot'.

The problem is that I do not know much about colors, and I'd like to achieve such effects in PIL for better performance.

解决方案

I figured out with the duplicate answer mentioned by @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)

The performance result is:

PIL: 1.7473899199976586

PLT: 10.632971412000188

They both give me similar result with hot color map.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值