Wasif Hyder
Wasif Hyder

Reputation: 1359

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. 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.

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.

Also, can you point out how to normalize the array since I'm unable to do so and can't find help anywhere.

Upvotes: 5

Views: 8730

Answers (1)

jnovacho
jnovacho

Reputation: 2903

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.

Upvotes: 2

Related Questions