1

I wrote this Python Program to create and save a matrix (2D Array) to a .png file. The program compiles and runs without any error. Even the IMAGE.png file is created but the png file won't open. When I try to open it in MSPaint, it says:

Cannot open image. Not a valid bitmap file or its format is not currently supported.

My objective is to create a RBG png image based on the numbers stored in the 2D Array.

Source Code:

    import numpy;
    import png;

    imagearray = numpy.zeros(shape=(512,512));

    /* Code to insert one '1', '2', '3' in certain locations 
       of the numpy 2D Array. Rest of the location by default stores zero '0'.*/


    f = open("IMAGE.png", 'wb');
    f.write(imagearray);
    f.close();

I don't understand where I went wrong as there is no error message. Please Help.

PS- I just want to save the matrix as an image file, so if you have a better and easy way of doing it in Python2.7, do suggest.

P. Camilleri
  • 12,664
  • 7
  • 41
  • 76
ArnabC
  • 181
  • 1
  • 3
  • 16
  • 1
    Please don't use semicolons in python, it's unnecessary. Also, your code is overindented. – P. Camilleri Jul 05 '17 at 09:46
  • Your code doesn't work because python doesn't know you're trying to save an image - all it sees is a binary file that you write an array to - `.png` is nothing more than part of the filename. A valid PNG file needs a header, which the file you create does not have – Eric Jul 05 '17 at 09:48

1 Answers1

2

Plot your image with matplotlib and save it.

import matplotlib.pyplot as plt
import numpy as np
a = np.random.uniform(size=(25, 25, 3))  # random 3D array
plt.imshow(a)
plt.savefig("img.png")

imshow() has various parameters of interest, amongst which interpolation (examples here) and cmap (colormap)

To remove the axes and whitespaces, as per this question:

plt.axis('off')
plt.savefig("img.png", bbox_inches='tight')
P. Camilleri
  • 12,664
  • 7
  • 41
  • 76
  • This is generally a bad way to save an image, as it falls foul of scaling, recoloring, and borders - there are better solutions within `matplotlib` for this, in in the duplicate question – Eric Jul 05 '17 at 09:51
  • @Eric So I'll delete my answer – P. Camilleri Jul 05 '17 at 09:53