0

I'm trying to save image (generated by GAN) in numpy.ndarray format with shape (row, col, channel) having float value. The first strategy I found here is using PIL

from PIL import Image

img_array = np.reshape(img_array, (row, col))
img_array *= 255
img = Image.fromarray(img_array.astype(np.uint8))
img.save('foo.png')

But after seeing the result (both when plotted with matplotlib or saved as image file), it creates white artifacts such like this

Sample of image in PIL

Compared to plotting the array straight into matplotlib, the result is better, but create margin in the image file when saved

Sample of image from matplotlib

How do I save the image in such way the quality is the same as the plot?

nb : I have checked the value using img_array.max() or img_array.min(), and yes the value is beyond 0-255 threshold

Muhamad Iqbal
  • 742
  • 1
  • 4
  • 17
  • To me this looks very curious: `np_image.astype(np.uint8)`. Try e.g. `x = np.array([1024, 255, 254, -1]); x.astype(np.uint8)`, and see the results. What is the range of values inside of `np_image`? Are there any negative values or values above 255? – Duck Dodgers Apr 04 '19 at 12:41
  • Try printing `np_image.max()` and `np_image.min()` after multiplying by 255. – Mark Setchell Apr 04 '19 at 12:55
  • @JoeyMallone the reason i'm using `astype(np.uint8)` is because I see lots of PIL answer on SO recommending conversion to `uint8`. One example : https://stackoverflow.com/questions/47290668/image-fromarray-just-produces-black-image – Muhamad Iqbal Apr 05 '19 at 13:56
  • @MuhamadIqbal, you could maybe add your test data to the question and make an [mcve] so that people here (including me, maybe) can test it on our system and run and see what is going and then give you feedback. From the looks of it, when you convert your `np_image` to `uint8`, it seems to clip all values above 255 to 255 and all values that are negative or zero are clipped to zero, hence my first comment. You can verify what values you have in your `np_image` as per Mark's suggestion. – Duck Dodgers Apr 08 '19 at 08:11
  • 1
    @JoeyMallone I modified the problem as per your advice, and you are right. The value (in float) clipped to 0-255 scale (after multiplied with 255 and converting to uint8) – Muhamad Iqbal Apr 22 '19 at 09:43

0 Answers0