I'm trying to convert a base64 representation of a JPEG to an image that can be used with OpenCV. The catch is that I'd like to be able to do this without having to physically save the photo (I'd like it to remain in memory). Is there an updated way of accomplishing this?
I'm using python 3.6.2 and OpenCV 3.3
Here is a partial example of the type of input I'm trying to convert:
/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAA....
I've already tried the solutions provided by these questions, but keep getting the same "bad argument type for built-in operation" error:
Base64 is only useful for very small images. This is because when it comes to larger images, the encoded size of a picture in bytes will end up being much larger than JPEGs or PNG files.
Base64 encoding allows you to turn different types of data (images included) into a readable string. Then, the string can be embedded directly into your code (e.g. the HTML code of your signature).
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With