How to convert a numpy python array to base64 output

I basically need to do this , but in Python instead of Javascript. I get the base64 encoded string from socketio connection, convert it to uint8 and work on it, then I need to convert it to base64 string so that I can send it.

So, up to this point I have it (I get the data dictionary from socketio server):

 import pickle import base64 from io import BytesIO from PIL import Image base64_image_string = data["image"] image = Image.open(BytesIO(base64.b64decode(base64_image_string))) img = np.array(image) 

How can I cancel this process to go from img to base64_image_string ?

UPDATE:
I solved this as follows (continued from the code snippet above):

 pil_img = Image.fromarray(img) buff = BytesIO() pil_img.save(buff, format="JPEG") new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8") 

Somewhat vaguely, new_image_string not identical to base64_image_string , but the image obtained from new_image_string looks the same, so I'm satisfied!

+5
source share
3 answers

from http://www.programcreek.com/2013/09/convert-image-to-string-in-python/ :

 import base64 with open("t.png", "rb") as imageFile: str = base64.b64encode(imageFile.read()) print str 

- binary read

https://docs.python.org/2/library/base64.html

0
source

I believe that with numpy.array buffer protocol support, you just need the following:

 processed_string = base64.b64encode(img) 

So for example:

 >>> encoded = b"aGVsbG8sIHdvcmxk" >>> img = np.frombuffer(base64.b64decode(encoded), np.uint8) >>> img array([104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100], dtype=uint8) >>> img.tobytes() b'hello, world' >>> base64.b64encode(img) b'aGVsbG8sIHdvcmxk' >>> 
0
source

I have the same problem. After some searching and trying, my final decision is almost the same as yours.

The only difference is that the base64 encoded string is png format data, so I need to change it from RGBA to RGB channels before converting to np.array:

 image = image.convert ("RGB") img = np.array(image) 

In the reverse process, you process the data as a JPEG , maybe this is the reason why new_image_string not identical to base64_image_string ?

0
source

Source: https://habr.com/ru/post/1266519/


All Articles