Highlight

2024-03-18

Don't forget to check your integer type!

"""PIL/Pillow Image.fromarray() doesn't check your array value types!"""

from PIL import Image
import numpy as np


im = Image.new("RGB", (2, 1))
im.putpixel((0, 0), (255, 0, 0))
im.putpixel((1, 0), (0, 255, 0))

a = np.array(im)
print("Good shape:", a.shape, a)
print("See?")
Image.fromarray(a, "RGB").show()

a = np.array([[[255, 0, 0], [0, 255, 0]]])
print("Bad shape:", a.shape, a)
print("Where'd the green pixel go?")
Image.fromarray(a, "RGB").show()

a = np.uint8(a)
print("Fixed shape:", a.shape, a)
print("If the green pixel disappeared, you forgot to cast to uint8.")
Image.fromarray(a, "RGB").show()

No comments:

Post a Comment