You have to convert you image back from a numpy array to an image which can then encoded correctly to Base64! What you now do is you encode a numpy array to base64 string which surely can't give the same result the online base64 tool gives!

What you need to do, pass your numpy array to cv2.imencode which returns a buffer image object and then you can convert it to base64

retval, buffer_img= cv2.imencode('.jpg', img)
data = base64.b64encode(buffer_img)

OR you can skip the img = cv2.imdecode(mydata, -1) and pass mydata directly to base64.b64encode(mydata) while the image is already stored the memory!

There is no openCV image, the openCV image is a ndArray. When you execute print(type(img)) you will get <class 'numpy.ndarray'>

Answer from Peshmerge on Stack Overflow
🌐
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 from io import BytesIO from PIL import Image img = Image.open('test.jpg') im_file = BytesIO() img.save(im_file, format="JPEG") im_bytes = im_file.getvalue() # im_bytes: image in binary format. im_b64 = base64.b64encode(im_bytes) In the above code, instead of saving the PIL Image ...
🌐
CodoRaven
codoraven.com › home › image & base64 | opencv vs pillow | python
Image & Base64 | OpenCV vs Pillow | Python - CodoRaven
March 16, 2023 - import base64 from io import BytesIO from PIL import Image # Pillow to base64 def pil_to_base64(pil_img): img_buffer = BytesIO() pil_img.save(img_buffer, format='JPEG') byte_data = img_buffer.getvalue() base64_str = base64.b64encode(byte_data) return base64_str # base64 to Pillow def base64_to_pil(base64_str): pil_img = base64.b64decode(base64_str) pil_img = BytesIO(pil_img) pil_img = Image.open(pil_img) return pil_img · import base64 import numpy as np import cv2 # OpenCV to base64 def cv2_base64(cv2_img): base64_str = cv2.imencode('.jpg', cv2_img)[1].tostring() base64_str = base64.b64encode(base64_str) return base64_str # base64 to OpenCV def base64_cv2(base64_str): imgString = base64.b64decode(base64_str) nparr = np.fromstring(imgString, np.uint8) cv2_img= cv2.imdecode(nparr, cv2.IMREAD_COLOR) return cv2_img
🌐
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 - This format is selected due to its lossless compression capability, ensuring no degradation of the original my_opencv_image quality. Additional configuration options can be adjusted using various flags, details of which can be found at the specified link. Caution: Usingencode_params=[int(cv2.IMWRITE_JPEG_QUALITY), 100]would result in loss, and the original image could not be restored. Even using 100 as the compression parameter, loss is inevitable. 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)
Top answer
1 of 2
87

You do not need to save the buffer to a file. The following script captures an image from a webcam, encodes it as a JPG image, and then converts that data into a printable base64 encoding which can be used with your JSON:

import cv2
import base64

cap = cv2.VideoCapture(0)
retval, image = cap.read()
retval, buffer = cv2.imencode('.jpg', image)
jpg_as_text = base64.b64encode(buffer)
print(jpg_as_text)
cap.release()

Giving you something starting like:

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCg

This could be extended to show how to convert it back to binary and then write the data to a test file to show that the conversion was successful:

import cv2
import base64

cap = cv2.VideoCapture(0)
retval, image = cap.read()
cap.release()

# Convert captured image to JPG
retval, buffer = cv2.imencode('.jpg', image)

# Convert to base64 encoding and show start of data
jpg_as_text = base64.b64encode(buffer)
print(jpg_as_text[:80])

# Convert back to binary
jpg_original = base64.b64decode(jpg_as_text)

# Write to a file to show conversion worked
with open('test.jpg', 'wb') as f_output:
    f_output.write(jpg_original)

To get the image back as an image buffer (rather than JPG format) try:

jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
image_buffer = cv2.imdecode(jpg_as_np, flags=1)
2 of 2
31

Some how the above answer doesn't work for me, it needs some update. Here is the new answer to this:

To encode for JSON:

import base64
import json
import cv2

img = cv2.imread('./0.jpg')
string = base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()
dict = {
    'img': string
}
with open('./0.json', 'w') as outfile:
    json.dump(dict, outfile, ensure_ascii=False, indent=4)

To decode back to np.array:

import base64
import json
import cv2
import numpy as np

response = json.loads(open('./0.json', 'r').read())
string = response['img']
jpg_original = base64.b64decode(string)
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
img = cv2.imdecode(jpg_as_np, flags=1)
cv2.imwrite('./0.jpg', img)

Hope this could help someone :P

🌐
OpenCV Q&A Forum
answers.opencv.org › question › 174328 › base64-to-mat-and-mat-to-base64
base64 to Mat and Mat to base64 - OpenCV Q&A Forum
I choose base64 because it's more easy format for beginner programmer in all language python, js, bash... Infact last problem to have is with using base64 format with openCV ... btw, you're probably not trying to encode a cv::Mat to base64, but an already png or jpg encoded image, right ?
🌐
GitHub
gist.github.com › HoweChen › 7cdd09b08147133d8e1fbe9b52c24768
[opencv_from_base64]read image from opencv with base64 encoding #OpenCV · GitHub
Save HoweChen/7cdd09b08147133d8e1fbe9b52c24768 to your computer and use it in GitHub Desktop. Download ZIP · [opencv_from_base64]read image from opencv with base64 encoding #OpenCV · Raw · opencv_from_base64.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
Find elsewhere
🌐
GitHub
github.com › RonnyldoSilva › Opencv_Mat_to_Base64
GitHub - RonnyldoSilva/OpenCV_Mat_to_Base64: What does this algorithm do? Convert Mat (OPENCV) to base64, and vise-versa. · GitHub
January 21, 2018 - What does this algorithm do? Convert Mat (OPENCV) to base64, and vise-versa. - RonnyldoSilva/OpenCV_Mat_to_Base64
Starred by 69 users
Forked by 22 users
Languages   C++
Top answer
1 of 5
20

I've been struggling with this issue for a while now and of course, once I post a question - I figure it out.

For my particular use case, I needed to convert the string into a PIL Image to use in another function before converting it to a numpy array to use in OpenCV. You may be thinking, "why convert to RGB?". I added this in because when converting from PIL Image -> Numpy array, OpenCV defaults to BGR for its images.

Anyways, here's my two helper functions which solved my own question:

import io
import cv2
import base64 
import numpy as np
from PIL import Image

# Take in base64 string and return PIL image
def stringToImage(base64_string):
    imgdata = base64.b64decode(base64_string)
    return Image.open(io.BytesIO(imgdata))

# convert PIL Image to an RGB image( technically a numpy array ) that's compatible with opencv
def toRGB(image):
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
2 of 5
19

Here an example for python 3.6 that uses imageio instead of PIL. It first loads an image and converts it to a b64_string. This string can then be sent around and the image reconstructed as follows:

import base64
import io
import cv2
from imageio import imread
import matplotlib.pyplot as plt

filename = "yourfile.jpg"
with open(filename, "rb") as fid:
    data = fid.read()

b64_bytes = base64.b64encode(data)
b64_string = b64_bytes.decode()

# reconstruct image as an numpy array
img = imread(io.BytesIO(base64.b64decode(b64_string)))

# show image
plt.figure()
plt.imshow(img, cmap="gray")

# finally convert RGB image to BGR for opencv
# and save result
cv2_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite("reconstructed.jpg", cv2_img)
plt.show()
🌐
CodeSpeedy
codespeedy.com › home › convert image to base64 string in python
Convert Image to Base64 String in Python - CodeSpeedy
September 19, 2023 - 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 · You must read the image file before you encode it.
🌐
CSDN
devpress.csdn.net › python › 630455f1c67703293080b5f7.html
Read a base 64 encoded image from memory using OpenCv python library_python_Mangs-Python
import base64 from PIL import Image import cv2 from StringIO import StringIO import numpy as np def readb64(base64_string): sbuf = StringIO() sbuf.write(base64.b64decode(base64_string)) pimg = Image.open(sbuf) return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR) cvimg = readb64('R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7') cv2.imshow(cvimg) # python # opencv ·
🌐
Upwork
upwork.com › project catalog › development & it › ai & machine learning › other ai & machine learning
You will get Numpy, OpenCV, Pil, Bytes, Base64, Network URL ,image type conversion. | Upwork
You will get Numpy, OpenCV, Pil, Bytes, Base64, Network URL ,image type conversion.
Numpy, OpenCV, Pil, Bytes, Base64, Network URL and other image type conversion, Python code implementation, carefully organized and summarized, commonly used in computer vision. Includes the following conversions: numpy to pil (opencv to pil) pil to numpy (pil to opencv) numpy to bytes (opencv to bytes) bytes to numpy (bytes to opencv) pil to bytes bytes to pil Web URL to pil Web URL to NUMPY (Web URL to OpenCV) Numpy to Base64 (OpenCV to Base64) Base64 to NUMPY (Base64 to OpenCV) pil to base64 Base64 to pil There are examples that can be run directly, and they will be used as soon as they ar
Price   $9.90
🌐
Stack Overflow
stackoverflow.com › questions › 65910507 › turning-an-open-cv-frame-into-a-base64-encoded-jpeg
python - Turning an Open CV frame into a Base64 encoded JPEG - Stack Overflow
def sendimage(): # produce thumbnail image thumbnail = imutils.resize(frame, width=320) # encode as base64 jpeg result, thumbnailjpg = cv2.imencode('.jpg', thumbnail, [cv2.IMWRITE_JPEG_QUALITY, 90]) encodedimage = "data:image/jpeg;base64,"+base64.b64encode(thumbnailjpg) # send via mqtt print("sending thubnail image") It seems to work as far as the cv2.imencode, but the base64.b64encode fails with. Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/L
🌐
PyPI
pypi.org › project › image-converters
image-converters · PyPI
June 20, 2023 - To use the ImageConverter class, you need to have OpenCV installed. You can install it using pip: ... from image_converter import ImageConverter # Create an instance of the ImageConverter class converter = ImageConverter() # Load an image converter.load_image('path/to/image.jpg') # Convert the image to bytes image_bytes = converter.image_to_bytes() # Convert bytes back to an image image = converter.bytes_to_image(image_bytes) # Encode the image as a base64 string encoded_image = converter.encode_image_to_base64() # Decode the base64 image back to an image decoded_image = converter.decode_base64_to_image(encoded_image) # Save the decoded image converter.save_decoded_image('path/to/output.jpg')
      » pip install image-converters
    
Published   Jun 20, 2023
Version   0.1.1
🌐
Stack Overflow
stackoverflow.com › questions › 64245597 › python-opencv-base64-issue-with-converting-frame-to-base64
Python + OpenCV + Base64: Issue with converting frame to base64 - Stack Overflow
import cv2 import base64 def footage_to_frame(video): vidcap = cv2.VideoCapture(video) frames = [] # read until no more frames exist in the video while True: success, frame = vidcap.read() if (success): frames.append(frame) else: # unable to read a frame break return frames def frames_to_base64(frames): frames_b64 = [] # iterate frames and convert each of them to base64 for frame in frames: frames_b64.append(base64.b64encode(frame)) return frames_b64
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-image-to-string-and-vice-versa
Python - Convert Image to String and vice-versa - GeeksforGeeks
July 23, 2025 - Image is read using image2string.read() and then encoded into a base64 string with base64.b64encode().