Image.fromarray just produces black image

后端 未结 1 585
心在旅途
心在旅途 2020-12-06 16:31

I\'m trying to save a numpy matrix as a grayscale image using Image.fromarray. It seems to work on a random matrix, but not on a particular one (where there sho

相关标签:
1条回答
  • 2020-12-06 16:48

    Image.fromarray is poorly defined with floating-point input; it's not well documented but the function assumes the input is laid-out as unsigned 8-bit integers.

    To produce the output you're trying to get, multiply by 255 and convert to uint8:

    z = (z * 255).astype(np.uint8)
    

    The reason it seems to work with the random array is that the bytes in this array, when interpreted as unsigned 8-bit integers, also look random. But the output is not the same random array as the input, which you can check by doing the above conversion on the random input:

    np.random.seed(0)
    zz = np.random.rand(size, size)
    Image.fromarray(zz, mode='L').save('pic1.png')
    

    Image.fromarray((zz * 255).astype('uint8'), mode='L').save('pic2.png')
    

    Since the issue doesn't seem to be reported anywhere, I reported it on github: https://github.com/python-pillow/Pillow/issues/2856

    0 讨论(0)
提交回复
热议问题