Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any good color map to convert gray-scale image to colorful ones using python's PIL? [duplicate]

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:

  1. Matplotlib is good for demo use, but bad performace for thounsands of images.
  2. Matplotlib colormaps
  3. 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'.

Matplotlib demo

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

like image 571
Adam Avatar asked Apr 17 '17 18:04

Adam


People also ask

How do I convert a color image to grayscale?

Change a picture to grayscale or to black-and-whiteRight-click the picture that you want to change, and then click Format Picture on the shortcut menu. Click the Picture tab. Under Image control, in the Color list, click Grayscale or Black and White.

How do you read a gray scale image in Python?

Convert an Image to Grayscale in Python Using the cv2. imread() Method of the OpenCV Library. Another method to get an image in grayscale is to read the image in grayscale mode directly, we can read an image in grayscale by using the cv2. imread(path, flag) method of the OpenCV library.


1 Answers

You can use the color maps from matplotlib and apply them without any matplotlib figures etc. This will make things much faster:

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')

Note:

  • If your input image is float, the values should be in the interval [0.0, 1.0].
  • If your input image is integer, the integers should be in the range [0, N) where N is the number of colors in the map. But you can resample the map to any number of values according to you needs:

    # If you need 8 color steps for an integer image with values from 0 to 7:
    cm = plt.get_cmap('gist_rainbow', lut=8)
    
like image 80
Philipp F Avatar answered Sep 28 '22 00:09

Philipp F