A document from MCS 275 Spring 2022, instructor David Dumas. You can also get the notebook file.

# Pillow (PIL module) demonstrations¶

David Dumas

## Importing the module¶

In [16]:
import PIL


In [22]:
# Let's open a JPEG photo
# This is a resized version of the photo from https://unsplash.com/photos/iHOZTi2niV4
img = PIL.Image.open("pillow-photo.jpg")
img

Out[22]:

## Converting¶

In [19]:
# To grayscale
# Note: .convert returns a new image
img_gray = img.convert("L")
img_gray.save("pillow-photo-gray.png")  # Write grayscale version to a PNG file
img_gray

Out[19]:
In [132]:
# To black and white (1-bit)
img_bw = img.convert("1",dither=PIL.Image.NONE)
img_bw

Out[132]:
In [134]:
# To black and white (1-bit)
# Without passing dither=PIL.Image.NONE, it uses patterned black/white pixels
# to give the impression of shades of gray.  This is called dithering.
# Your browser may resize the image a bit (making it smaller) resulting in some
# *actual* gray pixels being shown.
img_bw = img.convert("1")
img_bw

Out[134]:

## Cropping¶

In [35]:
# crop returns a new image
img_portion = img.crop( (85,52,245,200) )  # 4-tuple is (left_x, top_y, right_x, bottom_y)
img_portion

Out[35]:
In [135]:
# Check the size of the cropped portion
w,h = img_portion.size
w,h

Out[135]:
(160, 148)

## Resizing¶

In [136]:
# Resize returns a new image; it isn't a mutation!
w,h = img_portion.size
img_portion.resize( (3*w,int(1.5*h)) ) # (new width, new height)
# This is 3 times as wide, 1.5 times as tall
# Dimensions must be integers

Out[136]: