简体   繁体   English

Python - 将颜色贴图应用于灰度numpy数组并将其转换为图像

[英]Python - Applying a color map to a grayscale numpy array and converting it to an image

I want to achieve the gradient mapping effect that's available in Photoshop. 我想实现Photoshop中可用的渐变映射效果。 There's already a post that explains the desired outcome. 已经有一篇文章解释了预期的结果。 Also, this answer covers exactly what I want to do, however 此外, 这个答案完全涵盖了我想要做的事情

im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

is not working for me since I don't know how to normalize the array to values of 1.0. 因为我不知道如何将数组规范化为1.0的值,所以对我不起作用。

Below is my code as I intend for it to work. 以下是我打算使用它的代码。

im = Image.open(filename).convert('L') # Opening an Image as Grayscale
im_arr = numpy.asarray(im)             # Converting the image to an Array 

# TODO - Grayscale Color Mapping Operation on im_arr

im = Image.fromarray(im_arr)

Can anyone indicate the possible options and ideal way to apply a color map to this array? 任何人都可以指出将颜色贴图应用于此阵列的可能选项和理想方法吗? I don't want to plot it as there doesn't seem to be a simple way to convert a pyplot figure to an image. 我不想绘制它,因为似乎没有一种简单的方法将pyplot图形转换为图像。

Also, can you point out how to normalize the array since I'm unable to do so and can't find help anywhere. 此外,你能指出如何规范化数组,因为我无法这样做,并且无法在任何地方找到帮助。

To normalize the image you can use following procedure: 要标准化图像,您可以使用以下过程:

import numpy as np
image = get_some_image() # your source data
image = image.astype(np.float32) # convert to float
image -= image.min() # ensure the minimal value is 0.0
image /= image.max() # maximum value in image is now 1.0

The idea is to first shift the image, so the minimal value is zero. 我们的想法是首先移动图像,因此最小值为零。 This will take care of negative minimum as well. 这也将照顾负面的最小值。 Then you divide the image by the maximum value, so the resulting maximum is one. 然后将图像除以最大值,因此得到的最大值为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM