Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 710
CatCoder Avatar asked Sep 07 '25 02:09

CatCoder


1 Answers

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])
like image 114
Mark Setchell Avatar answered Sep 09 '25 21:09

Mark Setchell