Python 3 OpenCV & Pillow Script to Convert Image to Byte Array Full Project For Beginners

 

 

pip install opencv-python

 

 

pip install pillow

 

 

 

app.py`

 

 

OpenCV

 

 

import cv2

im = cv2.imread('test.jpg')
im_resize = cv2.resize(im, (500, 500))

is_success, im_buf_arr = cv2.imencode(".jpg", im_resize)
byte_im = im_buf_arr.tobytes()

# or using BytesIO
# io_buf = io.BytesIO(im_buf_arr)
# byte_im = io_buf.getvalue()

 

 

PIL

 

 

import io
from PIL import Image

im = Image.open('test.jpg')
im_resize = im.resize((500, 500))
buf = io.BytesIO()
im_resize.save(buf, format='JPEG')
byte_im = buf.getvalue()

Leave a Reply