Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 String to an Image that's compatible with OpenCV

Tags:

python

opencv

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:

  • Read a base 64 encoded image from memory using OpenCv python library
  • How to decode jpg image from memory?
  • Python: Alternate way to covert from base64 string to opencv
like image 511
Nathan Ortega Avatar asked Aug 28 '17 16:08

Nathan Ortega


People also ask

Is Base64 good for images?

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.

How does Base64 work for images?

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).

What is b64 format?

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.


1 Answers

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)
like image 100
Anthony Anyanwu Avatar answered Sep 24 '22 13:09

Anthony Anyanwu