Pono
Pono

Reputation: 11786

Speeding up loading of images in OpenCV vs Pillow

In my test python application I have a pretty standard JPEG file 1500 x 800 loaded into memory as buffer buf. That buffer needs to be decoded as image object so I can use it in OpenCV.

I know two solutions to this:

  1. Pillow or Pillow-SIMD:
from PIL import Image
from io import BytesIO

image = Image.open(BytesIO(buf))
  1. OpenCV:
import cv2
import numpy as np

np_buffer = np.frombuffer(buf, np.uint8)
image = cv2.imdecode(np_buffer, 128 | 1)

Now, the problem I am facing is performance. On average, it takes 0.1ms to load the image with Pillow and 30ms to load it with OpenCV.

Of course, there will be an additional overhead for converting Pillow image object into OpenCV format (numpy array) but still, is there anything that can be done to speed up loading and decoding image buffer in OpenCV?

I am using:

Python 3.8.5
Pillow-SIMD 7.0.0.post3
opencv-python 4.4.0.44
numpy 1.19.2

Upvotes: 6

Views: 6578

Answers (1)

Sandeep Kumar
Sandeep Kumar

Reputation: 274

for pillow instead of this

from PIL import Image
from io import BytesIO

image = Image.open(BytesIO(buf))

use this

from PIL import Image
from io import BytesIO
import numpy as np

image = Image.open(BytesIO(buf))
arr = np.array(image, dtype=np.uint8)

Then it will be a fair comparison, because pillow Image.open will not access pixel values. It does only when you try to plot the image or convert it to array. This should be comparable to your code for opencv.

Upvotes: 4

Related Questions