Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a numpy array (which is actually a BGR image) to Base64 string?

I know how to convert an image in the disk to base64 via reading the file. However, in this instance, I already have the image as a numpy array in my program, captured via a camera, like image[:,:,3]. How do I convert it to base64 string such that the image can still be recovered? I tried this.

from base64 import b64encode    
base64.b64encode(image)

It does indeed gives me a string, but when I tested with https://codebeautify.org/base64-to-image-converter, it could not render the image, which means there is something wrong in the conversion. Help please.

I know a solution is to write the image into the disk as a jpg picture and then read it into a base64 string. But obviously, I don't want a file i/o when I can avoid it.

like image 249
Della Avatar asked Oct 06 '17 05:10

Della


People also ask

How can I convert an image into base64 string using Python?

To convert the Image to Base64 String in Python, we have to use the Python base64 module that provides b64encode() method. Python base64. b64encode() function encodes a string using Base64 and returns that string.

Can we convert image to base64?

Convert Images to Base64Just select your JPG, PNG, GIF, Webp, or BMP picture or drag & drop it in the form below, press the Convert to Base64 button, and you'll get a base-64 string of the image. Press a button – get base64. No ads, nonsense, or garbage. Drag and drop your image here!

Can an image could be converted into a NumPy array?

Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format.


1 Answers

Here's an example to show what you need to do:

from PIL import Image
import io
import base64
import numpy

# creare a random numpy array of RGB values, 0-255
arr = 255 * numpy.random.rand(20, 20, 3)

im = Image.fromarray(arr.astype("uint8"))
#im.show()  # uncomment to look at the image
rawBytes = io.BytesIO()
im.save(rawBytes, "PNG")
rawBytes.seek(0)  # return to the start of the file
print(base64.b64encode(rawBytes.read()))

I can paste the string printed into the base64 image converter and it'll look similar to im.show(), as the site enlarges the image.

You may need to manipulate your array or provide an appropriate PIL mode when creating your image

like image 108
import random Avatar answered Oct 14 '22 13:10

import random