Skip to content

Instantly share code, notes, and snippets.

@mcvarer
Created December 14, 2020 14:50
Show Gist options
  • Save mcvarer/cf72a84429827510ec5f581cbfc575f6 to your computer and use it in GitHub Desktop.
Save mcvarer/cf72a84429827510ec5f581cbfc575f6 to your computer and use it in GitHub Desktop.
CV2_to_PIL_to_Byte
import os
import cv2
from PIL import Image
import io
with open(os.path.join(os.getcwd(),"mcv.jpeg"), "rb") as f:
image_bytes = f.read()
img_cv2 = cv2.imread(f.name)
print(type(img_cv2))
im_pil = Image.fromarray(img_cv2)
print(type(im_pil))
buf = io.BytesIO()
im_pil.save(buf, format='JPEG') # not local save only moment
byte_im = buf.getvalue()
im_pil = Image.open(io.BytesIO(byte_im))
print(type(im_pil))
##Output
# <class 'numpy.ndarray'>
# <class 'PIL.Image.Image'>
# <class 'PIL.JpegImagePlugin.JpegImageFile'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment