Change saturation with Imagekit, PIL or Pillow?
Asked Answered
A

3

13

How do I go about changing the saturation of an image using PIL or Pillow? Preferably I'd like to be able to use the solution together with the django-imagekit package. The reason I need to change the saturation is to create an effect where when the user hovers a black-and-white image it turns to colored.

Anticlinal answered 17/4, 2013 at 20:54 Comment(1)
Pillow is PIL, really.Gemini
S
4

If you're using django-imagekit, you can just use the bundled Adjust processor:

from imagekit.processors import Adjust
Adjust(color=0.5)

Under the hood, this will do exactly what @abarnert recommended.

Siberson answered 28/6, 2013 at 18:8 Comment(1)
Thanks @matthewwithanm. This is exactly what I was looking for. I think I ended up creating my own processor back then, which was a good practice but I was pretty sure it must be in imagekit somewhere.Anticlinal
E
32

You probably want ImageEnhance.Color.

img = PIL.Image.open('bus.png')
converter = PIL.ImageEnhance.Color(img)
img2 = converter.enhance(0.5)

This gives an image with half the "color" of the original. This isn't exactly the same thing as half the saturation (because half or double the saturation would usually underflow or overflow), but it's probably what you actually want most of the time. As the docs say, it works like the "color" knob on a TV.

Here's an example of the same image at 0.5, 1.0, and 2.0 color: enter image description here enter image description here enter image description here

Endorse answered 17/4, 2013 at 21:10 Comment(0)
G
6

If you want a greyscale image, simply convert it to the L (Luminance) mode:

greyscale = rgba_image.convert('L')

Applying that to my ninja:

cute ninja greyscale cute ninja

If you need intermediary steps, you need to convert the RGB value to HLS or HSV, adjust the saturation, then convert it back to RGB again. You could use colorsys for that, or adapt this numpy solution; I would expect the latter to perform better.

Gemini answered 17/4, 2013 at 21:5 Comment(1)
Or make a luminance-mode version and blend it with the original.Piecrust
S
4

If you're using django-imagekit, you can just use the bundled Adjust processor:

from imagekit.processors import Adjust
Adjust(color=0.5)

Under the hood, this will do exactly what @abarnert recommended.

Siberson answered 28/6, 2013 at 18:8 Comment(1)
Thanks @matthewwithanm. This is exactly what I was looking for. I think I ended up creating my own processor back then, which was a good practice but I was pretty sure it must be in imagekit somewhere.Anticlinal

© 2022 - 2024 — McMap. All rights reserved.