This post contains some useful python helper functions for image IO operations.
The key poitns of these helper functions are:
- Use BytesIO so that we don't need to save image to disk then reload it into memory.
- Encode images so that we can transfer images through network.
- The channel order used in openCV is BGR which is different from more widely used RGB. Therefore, if we use openCV to encode/decode an image, we need to convert the color if necessary.
1234567891011121314151617181920212223242526272829303132333435363738
import base64
import cv2
import io
import numpy as np
import imageio
def loadImageFromImageBytes(imageBytes):
npimg = np.fromstring(imageBytes.read(), np.uint8)
return cv2.cvtColor(cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED), cv2.COLOR_RGB2BGR)
def loadImageFromFlaskFileStorageObject(fileStorageObject):
npimg = np.fromstring(fileStorageObject.read(), np.uint8)
return cv2.cvtColor(cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED), cv2.COLOR_RGB2BGR)
def encodeImageUsingBase64(image, fileType='.png'):
assert "." in fileType, "File type must include dot(.)"
return base64.b64encode(cv2.imencode(fileType, image)[1].tostring()).decode('UTF-8')
def encodeImageBytesUsingBase64(imageBytes, fileType='.png'):
assert "." in fileType, "File type must include dot(.)"
return base64.b64encode(imageBytes.read()).decode('UTF-8')
# import matplotlib as mpl; mpl.use("Agg")
# import matplotlib.pyplot as plt
def pltSaveFigToBytes(plt, imageType="png"):
assert not "." in imageType, "Image type should not contain dot(.)"
imageBytes = io.BytesIO()
plt.savefig(imageBytes, format=imageType)
imageBytes.seek(0)
return imageBytes
def createGifWithBase64Encoding(frames, duration=1):
imageBytes = io.BytesIO()
imageio.mimwrite(imageBytes, frames, format="GIF", duration = duration)
imageBytes.seek(0)
return base64.b64encode(imageBytes.read()).decode("UTF-8")
----- END -----
©2019 - 2022 all rights reserved