I can't read image with open-cv from bytes

Viewed 776

Hey guys help me please.

I have flask rest api that receive multipart/form-data as image and I want to use opencv to process it .

My problem is I can't read image with cv2.imdecode.

This function is return none so what's wrong.

imgFile = request.files['image']
imgBuffer = imgFile.read() # <class 'bytes'>
#b'\xc3\xbf\xc3\x98\xc3\xbf\xc3\xa0\x00\x10'

img = np.frombuffer(imgBuffer, dtype='uint8') # <class 'numpy.ndarray'>
#[195 191 195 152 195 191 195 160   0  16]

img = cv2.imdecode(img, cv2.IMREAD_COLOR) # <class 'NoneType'>

My image is here

2 Answers

cv2.imdecode() expects to decode a JPEG-encoded or PNG-encoded image. Such an image would start with:

  • the JPEG signature ff d8 ff or
  • the PNG signature 89 50 4e 47 0d 0a 1a 0a

Yours does not. So it is probably just the raw, unencoded pixels and you probably just need:

img = np.array(imgBuffer).reshape((height,width))

Another clue is the size of your bytes buffer. If its size matches the height x width of your greyscale image (or 3x that if colour) it means your image is just pixel data, whereas you would expect a JPEG/PNG encoded image to be much smaller because it's compressed.

Try making the following changes to your code.

imgFile = request.files['image']
imgBuffer = imgFile.read() # <class 'bytes'>
#b'\xc3\xbf\xc3\x98\xc3\xbf\xc3\xa0\x00\x10'
my_img = cv2.imread(imgFile, 0)
my_img.imshow(my_img)
#stream = io.StringIO(imgBuffer.decode("UTF8"), newline=None)

#img = np.frombuffer(stream, dtype='uint8') # <class 'numpy.ndarray'>
#[195 191 195 152 195 191 195 160   0  16]

#img = cv2.imdecode(img, cv2.IMREAD_COLOR) # <class 'NoneType'>
Related