All formats

OpenCV (Python)

LanguagePython 3 (bindings of the C++ library)
LicenseApache 2.0
Repositorygithub.com/opencv/opencv-python (library: github.com/opencv/opencv)
Documentationimgcodecs reference
Depends onNumPy; libwebp is bundled in the wheels
Read / writeyes / yes, lossy, lossless, alpha; animation since 4.11

OpenCV is a computer vision library. cv2.imread and cv2.imwrite load and save WebP as NumPy arrays in BGR (or BGRA) channel order, which is what the rest of OpenCV expects. Use it when the image goes into or comes out of a vision pipeline; for general image conversion with metadata and animation, Pillow is better.

Installation#

Shell
pip install opencv-python
# servers without a GUI:
pip install opencv-python-headless

Basic usage: read and write WebP#

Python
import cv2

img = cv2.imread("in.webp", cv2.IMREAD_UNCHANGED)  # keeps alpha (4 channels) if present
if img is None:
    raise SystemExit("cannot read in.webp")
h, w = img.shape[:2]
print(w, "x", h, "channels:", img.shape[2] if img.ndim == 3 else 1)

small = cv2.resize(img, (w // 2, h // 2), interpolation=cv2.INTER_AREA)
ok = cv2.imwrite("out.webp", small, [cv2.IMWRITE_WEBP_QUALITY, 80])  # 1-100
if not ok:
    raise SystemExit("write failed")

How to write a lossless WebP#

A quality above 100 selects lossless compression:

Python
cv2.imwrite("lossless.webp", img, [cv2.IMWRITE_WEBP_QUALITY, 101])

How to encode WebP in memory#

imencode returns the file bytes, e.g. to send over HTTP:

Python
ok, buf = cv2.imencode(".webp", img, [cv2.IMWRITE_WEBP_QUALITY, 75])
if ok:
    data = buf.tobytes()

# and back
import numpy as np
decoded = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)

How to convert WebP to JPEG#

JPEG has no alpha; IMREAD_COLOR drops it while reading:

Python
img = cv2.imread("in.webp", cv2.IMREAD_COLOR)
cv2.imwrite("out.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 90])

How to read an animated WebP#

OpenCV 4.11 and later read and write animations with imreadanimation and imwriteanimation (tutorial):

Python
import cv2

ok, anim = cv2.imreadanimation("anim.webp")
if ok:
    for i, (frame, ms) in enumerate(zip(anim.frames, anim.durations)):
        print(i, frame.shape, ms, "ms")
    cv2.imwriteanimation("copy.webp", anim, [cv2.IMWRITE_WEBP_QUALITY, 90])

Tips#