Convert Color Photo to Black and White in Python

Hello Internet Programmers, today we convert color photo to black and white in python.

To convert color photo to black and white using python we are using python PIL library.

Installation

python3 -m pip install Pillow

If in case you have both Pythons installed and want to install this for Python3

PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities.

The Image module provides a class with the same name which is used to represent a PIL image.

The module also provides a number of factory functions, including functions to load images from files, and to create new images.

Image.convert() Returns a converted copy of this image.

Syntax: Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)

Parameters:
mode – The requested mode. See: Modes.
matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.
dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).
palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.
colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256.

Returns: An Image object.

Code

We are now convert the following picture into black and white picture using python.

convert photo to black and white photo using python
from PIL import Image

img = Image.open("color-to-bw/rdj.jpg")
contobw = img.convert("L")
contobw.save("color-to-bw/rdj-bw.jpg")
contobw.show()

# Follow @code_snail

Output

convert a color photo to black and white in python

Now convert your photo to black and white using python. Share it with your friends and happy coding 🙂

Explore pillow library: https://pillow.readthedocs.io/

Other python mini projects:

Leave a Comment

Copy link
Powered by Social Snap