When we are building web services using Python, we often send or receive images in base64 encoded format. However, when we are doing image processing tasks, we need to use PIL or OpenCV. In this post, I will share how to convert between OpenCV or PIL image and base64 encoded image.
base64 to PIL or OpenCV image
base64 to PIL Image
import base64 from io import BytesIO from PIL import Image with open("test.jpg", "rb") as f: im_b64 = base64.b64encode(f.read()) im_bytes = base64.b64decode(im_b64) # im_bytes is a binary image im_file = BytesIO(im_bytes) # convert image to file-like object img = Image.open(im_file) # img is now PIL Image object
In the above code, since
Image.open() only accepts image path or file-like
object, we first convert the base64 encoded image to
BytesIO object and then
read the image using PIL.
base64 to OpenCV Image
import base64 import numpy as np import cv2 with open("test.jpg", "rb") as f: im_b64 = base64.b64encode(f.read()) im_bytes = base64.b64decode(im_b64) im_arr = np.frombuffer(im_bytes, dtype=np.uint8) # im_arr is one-dim Numpy array _, img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR)
In the above code, we first convert binary image to Numpy array, then decode
the array with
img is an OpenCV image in Numpy ndarray format.
PIL or OpenCV image to base64
PIL Image to base64
import base64 from io import BytesIO from PIL import Image img = Image.open('test.jpg') im_file = BytestIO() img.save(im_file, format="JPEG") im_bytes = im_file.getvalue() # im_bytes: image in binary format. im_b64 = base64.b64encode(im_bytes)
In the above code, instead of saving the PIL Image object
img to the disk, we
save it to
im_file which is a file-like object. Note that in this case, we
need to specify the image format in
OpenCV to base64 image
import base64 import numpy as np import cv2 img = cv2.imread('test.jpg') _, im_arr = cv2.imencode('.jpg', img) # im_arr: image in Numpy one-dim array format. im_bytes = im_arr.tobytes() im_b64 = base64.b64encode(im_bytes)
In the above code, we first save the image in Numpy ndarray format to
which is an one-dim Numpy array. We then get the image in binary format by
method of this array.
License CC BY-NC-ND 4.0