I believe since numpy.arrays support the buffer protocol, 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'
>>>
Answer from juanpa.arrivillaga on Stack Overflow
🌐
Medium
annacsmedeiros.medium.com › efficient-image-processing-in-python-a-straightforward-guide-to-base64-and-numpy-conversions-e9e3aac13312
Efficient Image Processing in Python: A Straightforward Guide to Base64 and Numpy Conversions | by Anna C S Medeiros | Medium
March 30, 2024 - Therefore, we do not recommend this approach. import numpy as np import base64 import cv2 decoded = base64.b64decode(b64) nparr = np.frombuffer(decoded, np.uint8) bgr_img = cv2.imdecode(nparr, flags=cv2.IMREAD_COLOR)
Discussions

How to convert numpy image array (output from a DL model) to base64 and sent to front end html
How to handle image storage is a tricky topic, it depends on the scale, usage, and speed you want to achieve. If this is for a small scale application or a pet project I suggest saving those images to the file system and read it through Jinja, as opposed to converting it to base64, blob, storing into a db. More on reddit.com
🌐 r/flask
6
2
April 16, 2021
Black b64-encoded image from numpy array
# the function I use to convert array to b64 def numpy_to_b64(array): im_pil = Image.fromarray(array) if im_pil.mode != 'RGB': im_pil = im_pil.convert('RGB') buff = BytesIO() im_pil.save(buff, format="png") im_b64 = base64.b64encode(buff.getvalue()).decode("utf-8") return im_b64 @app.callback( ... More on community.plotly.com
🌐 community.plotly.com
2
1
April 17, 2019
python - Convert numpy array to base64 - Stack Overflow
I use: img = frame.copy() to take ... return a numpy array. How can i convert it into base64 to store in database and display it into web. Thanks for your help. ... The following code should work - note you'll have to switch around the format as needed, and the corresponding base64 string. In this example I've used PNG. from PIL import Image from io import ... More on stackoverflow.com
🌐 stackoverflow.com
November 27, 2019
python - Converting to base64 changes numpy array - Stack Overflow
I have a service which takes input a base64 image, converts it to numpy array, performs some operation on it and then converts it back to base64 image, which is sent as output. But the numpy array ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/flask › how to convert numpy image array (output from a dl model) to base64 and sent to front end html
r/flask on Reddit: How to convert numpy image array (output from a DL model) to base64 and sent to front end html
April 16, 2021 -

Fuys, I desperately need help.

I have a model loaded serverside which takes in images and gives a numpy array output of size (n,240,320,3), where n is the number of output images.

I want to convert these individual images to base64 strings, append it to a list and render_template a fron end html page with the list as data passed to it, so that i can put it in image tags.

im trying to do this with open cv, the following is the method im using:

'''

currimg = outputs[i,:,:,:] / 255

retval, buffer = cv2.imencode('.png',currimg)

pstr = base64.b64encode(buffer)

pstr = pstr.decode('utf-8')

proc64.append(pstr)

'''

when i do this normally in another python script, it works fine and gives me a proper base64 output.

but for some reason when i do it over the flask server, it always outputs some wrong base64 string (probably incomplete) and always gives a black image as output.

Any help would greatly be appreciated. Thanks in advance!

🌐
GitHub
gist.github.com › daino3 › b671b2d171b3948692887e4c484caf47
Converting an image data uri to (28, 28) numpy array and writing to csv · GitHub
image_b64 = dataurl.split(",")[1] binary = base64.b64decode(image_b64) image = np.asarray(bytearray(binary), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) Copy link · Copy Markdown · Author · Thanks, Kukunin. I'll give it a try. Sign up for free to join this conversation on GitHub.
🌐
Plotly
community.plotly.com › dash python
Black b64-encoded image from numpy array - Dash Python - Plotly Community Forum
April 17, 2019 - # the function I use to convert array to b64 def numpy_to_b64(array): im_pil = Image.fromarray(array) if im_pil.mode != 'RGB': im_pil = im_pil.convert('RGB') buff = BytesIO() im_pil.save(buff, format="png") im_b64 = base64.b64encode(buff.getvalue()).decode("utf-8") return im_b64 @app.callback( Output('display-img', 'children'), [Input('graph', 'clickData')] ) def display_click_data(clickData): if clickData: click_point_np = np.array([clickDat...
🌐
PyPI
pypi.org › project › image2base64
image2base64
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Find elsewhere
🌐
YouTube
youtube.com › luke chaffey
How to convert Python numpy array to base64 output - YouTube
python: How to convert Python numpy array to base64 outputThanks for taking the time to learn more. In this video I'll go through your question, provide vari...
Published   April 6, 2024
Views   34
🌐
jdhao's digital space
jdhao.github.io › 2020 › 03 › 17 › base64_opencv_pil_image_conversion
Conversion between base64 and OpenCV or PIL Image · jdhao's digital space
May 7, 2021 - import base64 import numpy as np import cv2 img = cv2.imread('test.jpg') _, im_arr = cv2.imencode('.jpg', img) # im_arr: image in Numpy one-dim array format. im_bytes = im_arr.tobytes() im_b64 = base64.b64encode(im_bytes) In the above code, we first save the image in Numpy ndarray format to im_arr which is a one-dim Numpy array. We then get the image in binary format by using the tobytes() method of this array. Convert OpenCV or PIL image to bytes.
🌐
C# Corner
c-sharpcorner.com › article › converting-image-to-base64-in-python
Converting Image To Base64 In Python
March 16, 2023 - In this article, we have learned how to convert an image to base64 format in Python using the Pillow and base64 modules. Encoding an image in base64 format can transfer it over the internet or store it in a text file.
🌐
CodeSpeedy
codespeedy.com › home › convert image to base64 string in python
Convert Image to Base64 String in Python - CodeSpeedy
September 19, 2023 - ... At first, we opened our file in ‘rb’ mode. Then we read the image file and encoded it with the following line: base64.b64encode(img_file.read()) – b64encode() is a method to encode the data into base64
🌐
NVIDIA Developer Forums
forums.developer.nvidia.com › autonomous machines › jetson & embedded systems › jetson nano
Convert cudaImage to base64 - Jetson Nano - NVIDIA Developer Forums
November 4, 2020 - Hi at all, I need to convert cudaImage object to base64 to stream it by websocket, is there a way to do that?
🌐
Bobby Hadz
bobbyhadz.com › blog › convert-image-to-base64-string-in-python
Convert an Image to Base64 String and vice versa in Python | bobbyhadz
April 11, 2024 - Use the file.read() method to read the image's contents. Use the base64.b64encode() method to encode the bytes using Base64 and return a bytes-like object.
Top answer
1 of 2
2

As suggested in the comments, I tried pyvips as below:

#!/usr/bin/env python3
import requests
import base64
import numpy as np
from PIL import Image
from io import BytesIO
from cv2 import imencode
import pyvips

def vips_2PNG(image,compression=6):
    # Convert PIL Image to Numpy array
    na = np.array(image)
    height, width, bands = na.shape

    # Convert Numpy array to Vips image
    dtype_to_format = {
       'uint8': 'uchar',
       'int8': 'char',
       'uint16': 'ushort',
       'int16': 'short',
       'uint32': 'uint',
       'int32': 'int',
       'float32': 'float',
       'float64': 'double',
       'complex64': 'complex',
       'complex128': 'dpcomplex',
    }
    linear = na.reshape(width * height * bands)
    vi = pyvips.Image.new_from_memory(linear.data, width, height, bands,dtype_to_format[str(na.dtype)])

    # Save to memory buffer as PNG
    data = vi.write_to_buffer(f".png[compression={compression}]")
    return data

def vips_including_reading_from_disk(image):
    # Load image from disk
    image = pyvips.Image.new_from_file('stuttgart.png', access='sequential')
    # Save to memory buffer as PNG
    data = image.write_to_buffer('.png')
    return data

def faster(image):
    image_arr = np.array(image)
    _, byte_data = imencode('.png', image_arr)        
    return byte_data

def orig(image, faster=True):    
    output_buffer = BytesIO()
    image.save(output_buffer, format='PNG')
    byte_data = output_buffer.getvalue()
    return byte_data

# img_url = "https://www.cityscapes-dataset.com/wordpress/wp-content/uploads/2015/07/stuttgart03.png"
filename = 'stuttgart.png'
img = Image.open(filename)

# r = orig(img)
# print(len(r))
# %timeit r = orig(img)

# r = faster(img)
# print(len(r))
# %timeit r = faster(img)

# r = vips_including_reading_from_disk(filename)
# print(len(r))
# %timeit r = vips_including_reading_from_disk(filename)

# r = vips_2PNG(img,0)
# print(len(r))
# %timeit r = vips_2PNG(img,0)

I was looking at trading off the compression parameter between file size and speed. Here is what I got - I wouldn't compare absolute values, but rather look at the performance relative to each other on my machine:

               Filesize        Time
PIL            1.7MB           1.12s
OpenCV         2.0MB           173ms   <--- COMPARE
vips(comp=0)   6.2MB           66ms
vips(comp=1)   2.0MB           132ms   <--- COMPARE
vips(comp=2)   2.0MB           153ms

I have put arrows next to the ones I would compare.

2 of 2
1

I use cv2.imencode which is 5x faster than before. Here's the code

import time
import requests
import base64
import numpy as np
from PIL import Image
from io import BytesIO
from cv2 import imencode


# input: single PIL image
def image_to_base64(image, faster=True):    
    now_time = time.time()
    if faster:        
        image_arr = np.array(image)
        _, byte_data = imencode('.png', image_arr)        
        print('--imencode: ' + str(time.time()-now_time))
    else:
        output_buffer = BytesIO()
        image.save(output_buffer, format='PNG')
        byte_data = output_buffer.getvalue()
        print('--image.save:' + str(time.time()-now_time))

    now_time = time.time()
    encoded_input_string  = base64.b64encode(byte_data)
    print('--base64.b64encode: ' + str(time.time()-now_time))

    now_time = time.time()
    input_string = encoded_input_string.decode("utf-8")
    print('--encoded_input_string.decode: ' + str(time.time()-now_time))  

    return input_string

img_url = "https://www.cityscapes-dataset.com/wordpress/wp-content/uploads/2015/07/stuttgart03.png"
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
now_time = time.time()
input_string = image_to_base64(img, faster=True)
print('total: ' + str(time.time()-now_time))

I wonder if there is any solution which can run faster.