Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Convert an Image to Differnt Modes Using Pillow in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

<PIL.PngImagePlugin.PngImageFile image mode=RGB size=37x54 at 0x11DB473D0>

Comments

  1. You can use the method Image.convert to convert a PIL.Image to different modes.

  2. ImageOps.grayscale(img) is equivalent to img.convert("L"). As a matter of fact, ImageOps.grayscale(img) directly calls img.convert("L") according to the implementation.

Gray Scale - “L” Mode

<PIL.Image.Image image mode=L size=37x54 at 0x7F4515F85160>
<PIL.Image.Image image mode=L size=37x54 at 0x7F4515F85748>

Black-and-White - “1” Mode

By default, dithering is applied (white noisies are added).

<PIL.Image.Image image mode=1 size=37x54 at 0x7F27CE694908>

You can disable dithering with the option dither=False.

<PIL.Image.Image image mode=1 size=37x54 at 0x7F4515F85E80>
<PIL.Image.Image image mode=1 size=37x54 at 0x7F458C8BF080>

When a black-and-white image is converted to a numpy array, a 2-dimensional array (instead of 3-dimensional) is returned.

array([[False, True, True, ..., True, True, True], [ True, True, True, ..., True, True, True], [ True, True, True, ..., True, True, True], ..., [False, True, True, ..., True, True, True], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False]])

You can also use Pillow to convert an image to other (colorfull) modes. For more details, please refer to Modes of the Method Image.convert .

--2020-02-16 11:00:53--  https://i.imgur.com/mB96s.png
Resolving i.imgur.com (i.imgur.com)... 127.0.0.1
Connecting to i.imgur.com (i.imgur.com)|127.0.0.1|:443... failed: Connection refused.
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=518x604 at 0x7F4515F7A160>
<PIL.Image.Image image mode=L size=518x604 at 0x7F4517776EF0>
<PIL.Image.Image image mode=L size=518x604 at 0x7F458C8BF400>
<PIL.Image.Image image mode=1 size=518x604 at 0x7F4515F59978>
<PIL.Image.Image image mode=1 size=518x604 at 0x7F458C8BF6A0>

Convert a RGBA Image to RGB

'RGBA'
'RGB'