Ben Chuanlong Du's Blog

It is never too late to learn.

Convert an Image to Differnt Modes Using Pillow in Python

In [1]:
import numpy as np
from PIL import Image, ImageOps
In [2]:
img = Image.open("../../home/media/poker/4h.png")
img
Out[2]:

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

In [14]:
ImageOps.grayscale(img)
Out[14]:
In [16]:
img.convert("L")
Out[16]:

Black-and-White - "1" Mode

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

In [25]:
img.convert("1")
Out[25]:

You can disable dithering with the option dither=False.

In [18]:
img_bw = img.convert("1", dither=False)
img_bw
Out[18]:
In [19]:
img_bw.convert("1", dither=False)
Out[19]:

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

In [22]:
np.array(img_bw)
Out[22]:
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 .

In [26]:
!wget https://i.imgur.com/mB96s.png
--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.
In [27]:
Image.open("mB96s.png")
Out[27]:
In [30]:
Image.open("mB96s.png").convert("L")
Out[30]:
In [34]:
def binarize(arr2d, threshold=200):
    arr2d = arr2d.copy()
    nrow, ncol = arr2d.shape
    for i in range(nrow):
        for j in range(ncol):
            if arr2d[i, j] > threshold:
                arr2d[i, j] = 255
            else:
                arr2d[i, j] = 0
    return arr2d
In [35]:
img_gs = Image.open("mB96s.png").convert("L")
Image.fromarray(binarize(np.array(img_gs)))
Out[35]:
In [36]:
Image.open("mB96s.png").convert("1", dither=False)
Out[36]:
In [37]:
Image.open("mB96s.png").convert("L").convert("1", dither=False)
Out[37]:

Convert a RGBA Image to RGB

In [4]:
img_rgba = img.convert("RGBA")
img_rgba.mode
Out[4]:
'RGBA'
In [5]:
img_rgb = img_rgba.convert("RGB")
img_rgb.mode
Out[5]:
'RGB'
In [ ]:
 

Comments