Skip to content

Use openCV to open images sent to ML models instead of Pillow #1708

@raphael0202

Description

@raphael0202

openCV is much, much faster:

image shape: (1200, 607, 3)
cv2.imdecode time: 0.010s
Image.open time: 0.028s
Image.open time (including np conversion): 0.348s
---
image shape: (400, 333, 3)
cv2.imdecode time: 0.002s
Image.open time: 0.002s
Image.open time (including np conversion): 0.113s
---
image shape: (4096, 3072, 3)
cv2.imdecode time: 0.206s
Image.open time: 0.247s
Image.open time (including np conversion): 5.123s

Script:

import io
import time

import cv2
import numpy as np
import requests
from PIL import Image

for image_url in (
    "https://world.openfoodfacts.org/images/products/281/304/702/0270/1.jpg",
    "https://images.openfoodfacts.org/images/products/210/010/055/9939/2.jpg",
    "https://prices.openfoodfacts.org/img/0100/NLhwECq0fH.webp",
):
    content_bytes = requests.get(image_url).content

    start_time = time.monotonic()
    image = cv2.imdecode(
        np.frombuffer(content_bytes, dtype=np.uint8), cv2.IMREAD_COLOR_RGB
    )
    print(f"image shape: {image.shape}")
    print(f"cv2.imdecode time: {time.monotonic() - start_time:.3f}s")

    start_time = time.monotonic()
    image = Image.open(io.BytesIO(content_bytes))
    image.load()  # Ensure the image is fully loaded
    print(f"Image.open time: {time.monotonic() - start_time:.3f}s")
    np.array(image.getdata()).reshape((image.height, image.width, 3))
    print(
        f"Image.open time (including np conversion): {time.monotonic() - start_time:.3f}s"
    )
``

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    To triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions