'Saving to .png from an array gives glitchy results

Not a big question, This is the code:

def rgb_to_png(rgb, path):
    rgbarray = np.array([np.array([x for x in i]) for i in rgb])
    rgbimage = PIL.Image.fromarray(rgbarray, "RGB")
    
    rgbimage.save(path+"\sample.png", "PNG", quality=100)

This is what it's supposed to look like: Image1

And this is what the code outputs: Output

It seems that it's saving each rgb value as a single pixel or something similar, but I don't get what's wrong in the code. What is happening in there?

(Note: Both pictures resolution is 128 by 128)



Solution 1:[1]

You need to specify the type of your Numpy arrays as you create them, else they will not be unsigned 8-bit like PIL expects:

rgbarray = np.array(..., np.uint8)

You can check yours with:

print(rgbarray.dtype)

Also, the last 2 parameters of your Image.save() are superfluous.

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