1

Using PIL, I can transform an image's color by first converting it to grayscale and then applying the colorize transform. Is there a way to do the same with scikit-image?

The difference with e.g. the question at Color rotation in HSV using scikit-image is that there the black stays black while in PIL colorize function, I can define both where I want black and white mapped to.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Bram
  • 618
  • 4
  • 14

1 Answers1

2

I think you want something like this to avoid any dependency on PIL/Pillow:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

def colorize(im,black,white):
    """Do equivalent of PIL's "colorize()" function"""
    # Pick up low and high end of the ranges for R, G and B
    Rlo, Glo, Blo = black
    Rhi, Ghi, Bhi = white

    # Make new, empty Red, Green and Blue channels which we'll fill & merge to RGB later
    R = np.zeros(im.shape, dtype=np.float)
    G = np.zeros(im.shape, dtype=np.float)
    B = np.zeros(im.shape, dtype=np.float)

    R = im/255 * (Rhi-Rlo) + Rlo
    G = im/255 * (Ghi-Glo) + Glo
    B = im/255 * (Bhi-Blo) + Blo

    return (np.dstack((R,G,B))).astype(np.uint8)


# Create black-white left-right gradient image, 256 pixels wide and 100 pixels tall
grad = np.repeat(np.arange(256,dtype=np.uint8).reshape(1,-1), 100, axis=0) 
Image.fromarray(grad).save('start.png')

# Colorize from green to magenta
result = colorize(grad, [0,255,0], [255,0,255])

# Save result - using PIL because I don't know skimage that well
Image.fromarray(result).save('result.png')

That will turn this:

enter image description here

into this:

enter image description here


Note that this is the equivalent of ImageMagick's -level-colors BLACK,WHITE operator which you can do in Terminal like this:

convert input.png -level-colors lime,magenta result.png

That converts this:

enter image description here

into this:

enter image description here


Keywords: Python, PIL, Pillow, image, image processing, colorize, colorise, colourise, colourize, level colors, skimage, scikit-image.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • I only used PIL to save a copy of the starting image and to save a copy of the resulting image so I could show both in my answer. The code will run just fine without both PIL interactions. – Mark Setchell Jun 27 '19 at 21:30
  • I marked the answer as being a solution as it shows what to do, but it should be pointed out that there's issues with the code if you really try to open an image from skimage (and potentially from PIL, didn't test that). Mainly to do with array dimensions being improperly accounted for, but easy enough to fix – Bram Jun 29 '19 at 15:13
  • You are most welcome to post any improvements you have as an answer - I’m always happy to learn and be shown better ways:-) – Mark Setchell Jun 29 '19 at 16:09