Home > other >  What does cv2.imencode() do, and how do i achieve the same with PIL?
What does cv2.imencode() do, and how do i achieve the same with PIL?

Time:12-09

I'm trying to make a rest API, and I came across this line of code-

_, img_encoded = cv2.imencode('.jpg', image)

What does this do? I unfortunately can't use OpenCV for m project, so is there any way I can achieve the same thing with PIL? Thanks, in advance!

CodePudding user response:

It writes a JPEG-compressed image into a memory buffer (RAM) instead of to disk.

With PIL:

#!/usr/bin/env python3

from PIL import Image
from io import BytesIO

# Create dummy red PIL Image
im = Image.new('RGB', (320,240), 'red')

# Create in-memory JPEG
buffer = BytesIO()
im.save(buffer, format="JPEG")

# Check first few bytes
JPEG = buffer.getvalue()
print(JPEG[:25])
  • Related