dridk
dridk

Reputation: 351

python PIL : shift the hue and saturation

From GIMP, I can shift the hue and saturation easily. For example, below are the original picture and the final results after set hue to -90 and saturation to 100.

How can I proceed to get the same results from Python PIL?

Original Picture

original picture

Final Picture

final picture

Upvotes: 2

Views: 7045

Answers (2)

CnrL
CnrL

Reputation: 2589

I would recommend converting your image into a numpy array, and then applying the matplotlib rgb_to_hsv function: http://matplotlib.org/api/colors_api.html#matplotlib.colors.rgb_to_hsv That way you can avoid the double for loop which is probably causing the pixel-by-pixel method using colorsys to be slow.

Upvotes: 3

Mark Ransom
Mark Ransom

Reputation: 308520

You can do it with a combination of the colorsys module and PIL, but it's kind of slow. colorsys allows you to change the color space to HSV where it's trivial to do hue and saturation modifications. I take the saturation to the power of 0.65 to approximate your example, it retains the range of 0.0-1.0 needed by colorsys while increasing the middle values.

import colorsys
from PIL import Image
im = Image.open(filename)
ld = im.load()
width, height = im.size
for y in range(height):
    for x in range(width):
        r,g,b = ld[x,y]
        h,s,v = colorsys.rgb_to_hsv(r/255., g/255., b/255.)
        h = (h + -90.0/360.0) % 1.0
        s = s**0.65
        r,g,b = colorsys.hsv_to_rgb(h, s, v)
        ld[x,y] = (int(r * 255.9999), int(g * 255.9999), int(b * 255.9999))

enter image description here

Upvotes: 3

Related Questions