Convert base64 String to an Image that's compatible with OpenCV
Here an example for python 3.6 that uses imageio instead of PIL. It first loads an image and converts it to a b64_string. This string can then be sent around and the image reconstructed as follows:
import base64
import io
import cv2
from imageio import imread
import matplotlib.pyplot as plt
filename = "yourfile.jpg"
with open(filename, "rb") as fid:
data = fid.read()
b64_bytes = base64.b64encode(data)
b64_string = b64_bytes.decode()
# reconstruct image as an numpy array
img = imread(io.BytesIO(base64.b64decode(b64_string)))
# show image
plt.figure()
plt.imshow(img, cmap="gray")
# finally convert RGB image to BGR for opencv
# and save result
cv2_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite("reconstructed.jpg", cv2_img)
plt.show()
I've been struggling with this issue for a while now and of course, once I post a question - I figure it out.
For my particular use case, I needed to convert the string into a PIL Image to use in another function before converting it to a numpy array to use in OpenCV. You may be thinking, "why convert to RGB?". I added this in because when converting from PIL Image -> Numpy array, OpenCV defaults to BGR for its images.
Anyways, here's my two helper functions which solved my own question:
import io
import cv2
import base64
import numpy as np
from PIL import Image
# Take in base64 string and return PIL image
def stringToImage(base64_string):
imgdata = base64.b64decode(base64_string)
return Image.open(io.BytesIO(imgdata))
# convert PIL Image to an RGB image( technically a numpy array ) that's compatible with opencv
def toRGB(image):
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
You can also try this:
import numpy as np
import cv2
def to_image_string(image_filepath):
return open(image_filepath, 'rb').read().encode('base64')
def from_base64(base64_data):
nparr = np.fromstring(base64_data.decode('base64'), np.uint8)
return cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
You can now use it like this:
filepath = 'myimage.png'
encoded_string = to_image_string(filepath)
load it with open cv like this:
im = from_base64(encoded_string)
cv2.imwrite('myloadedfile.png', im)