Sepia Toning with PIL

Fredrik Lundh | July 2008 (originally posted to the image-sig mailing list)

 

Q. I’m wondering if there’s some snazzy way to get sepia image conversion with PIL?

Simple sepia toning is usually done by converting the image to grayscale, and then attaching a brownish palette to the image. See e.g.

http://en.wikipedia.org/wiki/List_of_software_palettes#Color_gradient_palettes

To do this in PIL, convert the image to mode “L”, and use putpalette to attach a suitable palette to the image. Something like this might work:

from PIL import Image, ImageOps

def make_linear_ramp(white):
    # putpalette expects [r,g,b,r,g,b,...]
    ramp = []
    r, g, b = white
    for i in range(255):
        ramp.extend((r*i/255, g*i/255, b*i/255))
    return ramp

# make sepia ramp (tweak color as necessary)
sepia = make_linear_ramp((255, 240, 192))

im = Image.open("somefile.jpg")

# convert to grayscale
if im.mode != "L":
    im = im.convert("L")

# optional: apply contrast enhancement here, e.g.
im = ImageOps.autocontrast(im)

# apply sepia palette
im.putpalette(sepia)

# convert back to RGB so we can save it as JPEG
# (alternatively, save it in PNG or similar)
im = im.convert("RGB")

im.save("file.jpg")

A Django site. rendered by a django application. hosted by webfaction.