'cv2.imdecode returns None when trying to read bytestring image

I use this function to read a png and convert it into a byte array.

def generate_data(file):
    img = Image.open(os.path.join(PROJECT_ROOT, file))
    img_byte_arr = io.BytesIO()
    img.save(img_byte_arr, format="png")
    byte_arr = img_byte_arr.getvalue()
    return byte_arr

file1 = generate_data("file1.png")
file1 = np.fromstring(file1, np.uint8)

The np.array before looks like this: np.array: [98 39 92 ... 56 50 39]

file1 = cv2.imdecode(file1, cv2.IMREAD_COLOR)

file1: None

Why does cv2.imdecode(file1, cv2.IMREAD_COLOR) return None

Can anyone help me and explain why?



Solution 1:[1]

What are you actually trying to do?

Your code seems to read and decode a PNG image from disk into a PIL Image, then re-encode it back into a PNG in memory in a BytesIO. There's no point - you already had a PNG-encoded image on disk! If you want a PNG-encoded image in memory from a PNG-encoded file on disk, just do:

import pathlib

PNGencodedImage = pathlib.Path('image.png').read_bytes()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Setchell