Python - Helper Functions for Image IO

Subscribe Send me a message home page tags


This post contains some useful python helper functions for image IO operations.

The key poitns of these helper functions are:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 -----

Welcome to join reddit self-learning community.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png