Convert Between OpenCV and PIL Images | Python

In many circumstances, we need to convert a cv2 image to a PIL image (or PIL to cv2). Here, I will show you how to convert RGB/RGBA/grayscale images from cv2 to PIL or PIL to cv2.

Since the color channels are ordered differently in PIL and cv2 images, we have to convert the color format manually.

Pillow (PIL)OpenCV (cv2)
Colorful imageRGBBGR
Transparent imageRGBABGRA
Images of different color spaces
Images of different color spaces

1. Colorful Image (RGB)

Pillow to OpenCV

cv2_img = np.array(pil_img)
cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_RGB2BGR)

OpenCV to Pillow

cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(cv2_img)

2. Transparent Image (RGBA)

Pillow to OpenCV

cv2_img = np.array(pil_img)
cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_RGBA2BGRA)

OpenCV to Pillow

cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGRA2RGBA)
pil_img = Image.fromarray(cv2_img)

3. Grayscale Image

Pillow to OpenCV

cv2_img = np.array(pil_img)

OpenCV to Pillow

pil_img = Image.fromarray(cv2_img)

Full Example

Pillow to OpenCV

import cv2
from PIL import Image
import numpy as np  # remember to import numpy

# read images
pil_img_jpg = Image.open("test_images/test1.jpg")
pil_img_png = Image.open("test_images/test2.png")
pil_img_gray = Image.open("test_images/test1.jpg").convert("L")

# convert Pillow (RGB) to OpenCV (BGR)
cv2_img_jpg = np.array(pil_img_jpg)
cv2_img_jpg = cv2.cvtColor(cv2_img_jpg, cv2.COLOR_RGB2BGR)

# convert Pillow (RGBA) to OpenCV (BGRA)
cv2_img_png = np.array(pil_img_png)
cv2_img_png = cv2.cvtColor(cv2_img_png, cv2.COLOR_RGBA2BGRA)

# convert Pillow to OpenCV (grayscale)
cv2_img_gray = np.array(pil_img_gray)

OpenCV to Pillow

import cv2
from PIL import Image
import numpy as np  # remember to import numpy

# read images
cv2_img_jpg = cv2.imread("test_images/test1.jpg")
cv2_img_png = cv2.imread("test_images/test2.png", cv2.IMREAD_UNCHANGED)
cv2_img_gray = cv2.imread("test_images/test1.jpg", cv2.IMREAD_GRAYSCALE)

# convert OpenCV (BGR) to Pillow (RGB)
cv2_img_jpg = cv2.cvtColor(cv2_img_jpg, cv2.COLOR_BGR2RGB)
pil_img_jpg = Image.fromarray(cv2_img_jpg)

# convert OpenCV (BGRA) to Pillow (RGBA)
cv2_img_png = cv2.cvtColor(cv2_img_png, cv2.COLOR_BGRA2RGBA)
pil_img_png = Image.fromarray(cv2_img_png)

# convert OpenCV to Pillow (grayscale)
pil_img_gray = Image.fromarray(cv2_img_gray)

Syntax

cv2.cvtColor(src, code[, dst[, dstCn]])

Parameters:

  • src: input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.
  • dst: output image of the same size and depth as src.
  • code: color space conversion code (see ColorConversionCodes).
  • dstCn: number of channels in the destination image; if the parameter is 0, the number of channels is derived automatically from src and code.

Returns:

  • The converted image (Numpy array)

References

Avatar photo
Steins

Developer & AI Researcher. Write about AI, web dev/hack.