@Andy Rosenblum's works, and it might be the best solution if using the outdated cv python API (vs. cv2).

However, because this question is equally interesting for users of the latest versions, I suggest the following solution. The sample code below may be better than the accepted solution because:

  1. It is compatible with newer OpenCV python API (cv2 vs. cv). This solution is tested under opencv 3.0 and python 3.0. I believe only trivial modifications would be required for opencv 2.x and/or python 2.7x.
  2. Fewer imports. This can all be done with numpy and opencv directly, no need for StringIO and PIL.

Here is how I create an opencv image decoded directly from a file object, or from a byte buffer read from a file object.

import cv2
import numpy as np

#read the data from the file
with open(somefile, 'rb') as infile:
     buf = infile.read()

#use numpy to construct an array from the bytes
x = np.fromstring(buf, dtype='uint8')

#decode the array into an image
img = cv2.imdecode(x, cv2.IMREAD_UNCHANGED)

#show it
cv2.imshow("some window", img)
cv2.waitKey(0)

Note that in opencv 3.0, the naming convention for the various constants/flags changed, so if using opencv 2.x, you will need to change the flag cv2.IMREAD_UNCHANGED. This code sample also assumes you are loading in a standard 8-bit image, but if not, you can play with the dtype='...' flag in np.fromstring.

Answer from svohara on Stack Overflow
Top answer
1 of 6
21

@Andy Rosenblum's works, and it might be the best solution if using the outdated cv python API (vs. cv2).

However, because this question is equally interesting for users of the latest versions, I suggest the following solution. The sample code below may be better than the accepted solution because:

  1. It is compatible with newer OpenCV python API (cv2 vs. cv). This solution is tested under opencv 3.0 and python 3.0. I believe only trivial modifications would be required for opencv 2.x and/or python 2.7x.
  2. Fewer imports. This can all be done with numpy and opencv directly, no need for StringIO and PIL.

Here is how I create an opencv image decoded directly from a file object, or from a byte buffer read from a file object.

import cv2
import numpy as np

#read the data from the file
with open(somefile, 'rb') as infile:
     buf = infile.read()

#use numpy to construct an array from the bytes
x = np.fromstring(buf, dtype='uint8')

#decode the array into an image
img = cv2.imdecode(x, cv2.IMREAD_UNCHANGED)

#show it
cv2.imshow("some window", img)
cv2.waitKey(0)

Note that in opencv 3.0, the naming convention for the various constants/flags changed, so if using opencv 2.x, you will need to change the flag cv2.IMREAD_UNCHANGED. This code sample also assumes you are loading in a standard 8-bit image, but if not, you can play with the dtype='...' flag in np.fromstring.

2 of 6
16

another way,

also in the case of a reading an actual file this will work for a unicode path (tested on windows)

with open(image_full_path, 'rb') as img_stream:
    file_bytes = numpy.asarray(bytearray(img_stream.read()), dtype=numpy.uint8)
    img_data_ndarray = cv2.imdecode(file_bytes, cv2.CV_LOAD_IMAGE_UNCHANGED)
    img_data_cvmat = cv.fromarray(img_data_ndarray) #  convert to old cvmat if needed
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-opencv-imdecode-function
OpenCV - imdecode() Function in Python - GeeksforGeeks
July 23, 2025 - import numpy as np import urllib.request import cv2 url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png' with urllib.request.urlopen(url) as resp: i = np.asarray(bytearray(resp.read()), dtype="uint8") i = cv2.imdecode(i, 0) cv2.imwrite("result.jpg", i) Output: Explanation: Similar to the first example, the image is fetched and converted into a NumPy array.
Discussions

cv2 imdecode after transporting an image via multipart form
I may be misunderstanding you here, but why are you trying to decode an array of image pixel bytes into a jpeg-encoded image? If you have pixels and want jpeg then you need to encode it to be jpeg. If you do actually want jpeg on the client side then I’d recommend encoding it on the backend before sending it back, since the jpeg should be less data to send than the raw array. As a note on your question, context is all well and good (and definitely better than not enough information), but what’s most helpful is a “minimal working example” (MWE), which is the smallest amount of code you could get to replicate the issue you’re having. That generally helps to make the code short enough for people to be able to read and test it (without needing to get up to speed on your entire project), and the process of making such an example will frequently lead you to discover the solution yourself, or at least a very specific description of the issue which is likely easier to solve than the initial problem statement you start out with. More on reddit.com
🌐 r/learnpython
3
1
November 8, 2021
python - Get back a numpy array from JPEG encoded (by cv2.imencode) bytearray - Stack Overflow
import cv2 img = cv2.imread('a.jpg') img_encoded = cv2.imencode('.jpg', img)[1] # memory buffer, type returns # encode as bytes object, so I can send img_bytes = bytearray(img_encoded) # type bytes · How can I reverse the process to get the image as a numpy array in the server end? I can use imdecode ... More on stackoverflow.com
🌐 stackoverflow.com
February 14, 2021
python - How to encode a numpy array with PIL, like opencv's cv2.imencode()? - Stack Overflow
I'm making a REST API with flask, and I want to send an image to my server. So far I did- from PIL import Image, ImageOps import cv2 image= Image.open("image.jpg") size = (224, 224) imag... More on stackoverflow.com
🌐 stackoverflow.com
Python - byte image to NumPy array using OpenCV - Stack Overflow
I created a 2x2 JPEG image to test this. The image has white, red, green and purple pixels. I used cv2.imdecode and numpy.frombuffer More on stackoverflow.com
🌐 stackoverflow.com
🌐
ProgramCreek
programcreek.com › python › example › 89456 › cv2.imdecode
Python Examples of cv2.imdecode
Args: content (bytes): Image bytes ... image array. """ imread_flags = { 'color': cv2.IMREAD_COLOR, 'grayscale': cv2.IMREAD_GRAYSCALE, 'unchanged': cv2.IMREAD_UNCHANGED } img_np = np.fromstring(content, np.uint8) flag = imread_flags[flag] if isinstance(flag, str) else flag img = cv2.imdecode(img_np, flag) return img ... def capture(self, method=FROM_SHELL) -> Union[np.ndarray, None]: """ Capture the screen. :return: a cv2 image as numpy ndarray """ ...
🌐
Reddit
reddit.com › r/learnpython › cv2 imdecode after transporting an image via multipart form
r/learnpython on Reddit: cv2 imdecode after transporting an image via multipart form
November 8, 2021 -

I have my question posted on SO so I will drop the link instead of retyping everything. I did ask earlier about making the multipart encoded message and figured that out but I can't get the jpeg to build on the clients end.

https://stackoverflow.com/questions/69878024/cv2-imdecode-imencode-and-transporting-images-over-http-using-multipart-encoder

tl;dr is I send a request for object detection to a flask app, it replies with multipart encoded response with JSON about detection and an image converted from cv2.decode (numpy.ndarray) using .tobytes() for HTTP transport. The client receives the multipart, decodes the JSON but cant decode the image into a jpeg.

Here are some logs for the flow of what I am dealing with.

  # Grabbing image using an http request and converting into a jpeg
  11/07/21 20:44:30.623202 zm_mlapi[37535] DBG1 Media:659 ['std.out' --> image from ZM API as response.content - type(img) = <class 'bytes'> - len(img) = 205125]
  11/07/21 20:44:30.627857 zm_mlapi[37535] DBG1 Media:661 ['std.out' --> after np.asarray(bytearray(img), np.uint8) - type(img) = <class 'numpy.ndarray'> - len(img) = 205125]
  11/07/21 20:44:30.658582 zm_mlapi[37535] DBG1 Media:663 ['std.out' --> after cv2.imdecode(img, cv2.IMREAD_COLOR) - type(img) = <class 'numpy.ndarray'> - len(img) = 1080]
  11/07/21 20:44:30.67595 zm_mlapi[37535] DBG2 pyzm_utils:386 [resize:img: success using resize=800.0 - original dimensions: 1920*1080 - resized dimensions: 450*800]
  11/07/21 20:44:30.678568 zm_mlapi[37535] DBG1 Media:681 ['std.out' --> after resize - type(img) = <class 'numpy.ndarray'> - len(img) = 450]
  # returned image to the class that requested it (ML Pipeline)
  11/07/21 20:44:30.687835 zm_mlapi[37535] DBG1 detect_sequence:1048 ['std.out' --> DETECT STREAM: FRAME RETURNED FROM MEDIA CLASS --> type(frame) = <class 'numpy.ndarray'> - len(frame) = 450]
  11/07/21 20:44:33.582062 zm_mlapi[37535] DBG1 detect_sequence:1656 ['std.out' --> before returning matched data - type(matched_data['image']) = <class 'numpy.ndarray'> - len(matched_data['image']) = 450]
   # Return image to the flask app, now the flask app has to construct a response with JSON and the image
  11/07/21 20:44:33.588139 zm_mlapi[37535] DBG1 mlapi:587 ['std.out' --> type(matched_data['image']) = <class 'numpy.ndarray'> - len(matched_data['image']) = 450]
  11/07/21 20:44:33.591981 zm_mlapi[37535] DBG1 mlapi:590 ['std.out' --> before converting using .tobytes() - type(img) = <class 'numpy.ndarray'> - len(img) = 450]
  11/07/21 20:44:33.596642 zm_mlapi[37535] DBG1 mlapi:594 ['std.out' --> after converting using .tobytes() - type(img) = <class 'bytes'> - len(img) = 1080000]
  11/07/21 20:44:33.611218 zm_mlapi[37535] DBG1 mlapi:611 ['std.out' --> multipart MIME TYPE -> multipart/form-data; boundary=e7f7b825a51d4184ad7f12e7bbc6f411]
  # flask app returns the response to the client
 11/07/21 21:00:58.393864 zmesdetect_m4[102768] DBG1 zm_detect:418 ['std.out' --> got json data]
  11/07/21 21:00:58.395459 zmesdetect_m4[102768] DBG1 zm_detect:414 ['std.out' --> got an image with Content-Type - b'application/octet']
  11/07/21 21:00:58.396815 zmesdetect_m4[102768] DBG1 zm_detect:422 ['std.out' --> success = True]
  11/07/21 21:00:58.398169 zmesdetect_m4[102768] DBG1 zm_detect:423 ['std.out' --> img - type(img) = <class 'bytes'> - len(img) = 1080000]
  11/07/21 21:00:58.39958 zmesdetect_m4[102768] DBG1 zm_detect:424 ['std.out' --> img[:50] = b'\\gu\\gu\\gu]hv^iw_jx`kyalzgr\x80kv\x84it\x82it\x82it\x82it\x82it\x82it\x82ju']
  11/07/21 21:00:58.401012 zmesdetect_m4[102768] DBG1 zm_detect:426 ['std.out' --> img after np.frombuffer(img, dtype=np.uint8) -> type(np_img) = <class 'numpy.ndarray'>]
  11/07/21 21:00:58.402911 zmesdetect_m4[102768] DBG1 zm_detect:430 ['std.out' --> img after np_img.copy() -> type(np_img) = <class 'numpy.ndarray'>]
  11/07/21 21:00:58.404296 zmesdetect_m4[102768] DBG1 zm_detect:432 ['std.out' --> len(np_img)=1080000]
  11/07/21 21:00:58.405619 zmesdetect_m4[102768] DBG1 zm_detect:433 ['std.out' --> attempting to decode numpy array into a jpeg]
  11/07/21 21:00:58.407144 zmesdetect_m4[102768] DBG1 zm_detect:442 ['std.out' --> img after cv2.imdecode -> type(new_img) = <class 'NoneType'>]
  11/07/21 21:00:58.408474 zmesdetect_m4[102768] DBG1 zm_detect:448 ['std.out' --> exiting due to image error]
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-opencv-imencode-function
Python OpenCV - imencode() Function - GeeksforGeeks
July 23, 2025 - import numpy as np import cv2 as cv img = cv.imread('/content/OpenCV.png') img_encode = cv.imencode('.jpg', img)[1] data_encode = np.array(img_encode) byte_encode = data_encode.tobytes() print(byte_encode)
🌐
Stack Overflow
stackoverflow.com › questions › 70278403 › how-to-encode-a-numpy-array-with-pil-like-opencvs-cv2-imencode
python - How to encode a numpy array with PIL, like opencv's cv2.imencode()? - Stack Overflow
from PIL import Image, ImageOps import cv2 image= Image.open("image.jpg") size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) image= np.array(image) _, JPEG = cv2.imencode('.jpg', image) response_raw = requests.post(test_url, data=JPEG.tostring(), headers=headers)
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python numpy array to cv2 mat
5 Best Ways to Convert Python Numpy Array to cv2 Mat - Be on the Right Side of Change
February 20, 2024 - If numpy array represents raw image data, you can use cv2.imdecode() to interpret the array as image data and return a Mat object.
Find elsewhere
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 202145 › how-to-decode-by-imdecode
how to decode by imdecode - OpenCV Q&A Forum
October 30, 2018 - no, the input to imdecode is a (1d) byte array like a file on disc (including headers, compressed pixels, etc) that's not the same as a numpy image in memory, which is, what you're trying above ... I've just tried to read an image from a buffer in memory as is.
Top answer
1 of 2
47

I created a 2x2 JPEG image to test this. The image has white, red, green and purple pixels. I used cv2.imdecode and numpy.frombuffer

import cv2
import numpy as np

f = open('image.jpg', 'rb')
image_bytes = f.read()  # b'\xff\xd8\xff\xe0\x00\x10...'

decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)

print('OpenCV:\n', decoded)

# your Pillow code
import io
from PIL import Image
image = np.array(Image.open(io.BytesIO(image_bytes))) 
print('PIL:\n', image)

This seems to work, although the channel order is BGR and not RGB as in PIL.Image. There are probably some flags you might use to tune this. Test results:

OpenCV:
 [[[255 254 255]
  [  0   0 254]]

 [[  1 255   0]
  [254   0 255]]]
PIL:
 [[[255 254 255]
  [254   0   0]]

 [[  0 255   1]
  [255   0 254]]]
2 of 2
1

I searched all over the internet finally I solved:

NumPy array (cv2 image) - Convert

NumPy to bytes

and

bytes to NumPy

:.

#data = cv2 image array
def encodeImage(data):
    #resize inserted image
    data= cv2.resize(data, (480,270))
    # run a color convert:
    data= cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
    return bytes(data) #encode Numpay to Bytes string



def decodeImage(data):
    #Gives us 1d array
    decoded = np.fromstring(data, dtype=np.uint8)
    #We have to convert it into (270, 480,3) in order to see as an image
    decoded = decoded.reshape((270, 480,3))
    return decoded;

# Load an color image
image= cv2.imread('messi5.jpg',1)

img_code = encodeImage(image) #Output: b'\xff\xd8\xff\xe0\x00\x10...';
img = decodeImage(img_code) #Output: normal array
cv2.imshow('image_deirvlon',img);
print(decoded.shape)

You can get full code from here

🌐
HotExamples
python.hotexamples.com › examples › cv2 › - › imdecode › python-imdecode-function-examples.html
Python imdecode Examples, cv2.imdecode Python Examples - HotExamples
def callback(self, data): global video global image_time #TODO If image_time is not matching with the time in odom_msgs, both computers are out of sync image_time = data.header.stamp.secs np_arr = np.fromstring(data.data, np.uint8) cv_image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) np_arr = np.fromstring(data.data, np.uint8) cv_image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) final_img = process_image(cv_image) ... def convertimagetoopencvarray(image): """ convert image from jpg to and numpy array to be able to apply the opencv methods on the image """ image_array = np.asarray(bytearray(image), dtype="uint8") image_prep = cv2.imdecode(image_array, cv2.IMREAD_GRAYSCALE) # image to show the detected artifacts on later in the main thread image_show = cv2.imdecode(image_array, cv2.IMREAD_ANYCOLOR) return image_prep, image_show
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 186584 › cv2imencode-cv2imdecode-output-issue
cv2.imencode / cv2.imdecode output issue - OpenCV Q&A Forum
March 13, 2018 - import cv2 import socket import pickle import numpy as np import time import sys # Capture picture cap = cv2.VideoCapture('sample.jpg') ret, frame = cap.read() #print frame as is print (frame) #encode data ready for sending pack_data = cv2.imencode('.jpeg', frame)[1].tobytes() # just a simple output separator print('--------------------------------------------') #deode encoded data back into array i = cv2.imdecode(np.fromstring(pack_data, dtype=np.uint8),cv2.IMREAD_COLOR) #print array after it is decoded print (i) ---------- BEFORE ENCODING [[[237 244 243] [249 255 255] [255 246 250] ..., [242
🌐
OpenCV
docs.opencv.org › 3.4.20 › d4 › da8 › group__imgcodecs.html
OpenCV: Image file reading and writing
Reads an image from a buffer in memory · The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns an empty matrix ( Mat::data==NULL )
🌐
Dynaikon
dynaikon.com › trap-docs › _autosummary › DynAIkonTrap.imdecode.html
DynAIkonTrap.imdecode - DynAIkonTrap 1.5.1 documentation
Wraps around the OpenCV imdecode method, to decode colour jpeg images produces a numpy ndarray in BGR format of uncompressed data
🌐
Cloudinary
cloudinary.com › home › convert image to numpy array: methods, tips, and examples
Convert Image to NumPy Array: Methods, Tips, and Examples | Cloudinary
January 24, 2026 - The cv2.imread() function reads the file and returns a NumPy array automatically: import cv2 # Load the image using OpenCV img = cv2.imread("../images/butterfly-9986828_640.jpg") print(type(img)) # <class 'numpy.ndarray'> print(img.shape) # ...
🌐
Stack Overflow
stackoverflow.com › questions › 38190679 › trying-to-read-numpy-array-into-opencv-cv2-imdecode-returns-empty-argument
python - Trying to read numpy array into opencv - cv2.imdecode returns empty argument - Stack Overflow
August 23, 2016 - #import packages import cv2 from matplotlim import pyplot as plt import os from astropy.io import fits from skimage import img_as_uint import numpy as np #create array with filenames data = [] for root, dirs, files in os.walk(r'/Users/hannah/Desktop/firefountain-testset'): for file in files: if file.endswith('.fits'): data.append(file) #start my loop through the folder for i in data: fn = i #read fits image data hdulist = fits.open(fn) img_data = hdulist[1].data #put fits data into array with dtype set as original imgraw=np.array(img_data, dtype = np.uint8) #convert to uint16 img = img_as_uint
🌐
GitHub
gist.github.com › kylehounslow › 767fb72fde2ebdd010a0bf4242371594
Send and receive images using Flask, Numpy and OpenCV · GitHub
Thanks for this @kylehounslow passing cv2.IMREAD_COLOR to cv2.imdecode was where I was missing it.[ np.fromstring ](https://numpy.org/devdocs/reference/generated/numpy.fromstring.html) is deprecated tho. np.drombuffer should be used · Copy link · Anyone that wants to get image from client and store in buffer can use this snippet below for flask ·
🌐
Python Examples
pythonexamples.org › python-opencv-read-image-cv2-imread
OpenCV Read Image - cv2 imread() - 3 Python Examples
In this tutorial, we shall learn in detail how to read an image using OpenCV, by considering some of the regular scenarios. We will also learn the order in which imread() function decodes the color channels from an image and how imread() treats different image extensions. The syntax of cv2.imread() ...