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.

Source Code:

import numpy;
import png;

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

/* Code to insert one '1' 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.

Thank You.

ArnabC
  • 181
  • 1
  • 3
  • 16
  • A PNG file is not just a dump of the data in an array. You need to use a library to create a PNG file from a numpy array. Something like [Pillow](https://python-pillow.org/), or [pypng](https://pypi.python.org/pypi/pypng), or the small module that I created called [numpngw](https://pypi.python.org/pypi/numpngw). – Warren Weckesser May 06 '17 at 16:34

2 Answers2

1

Not every array is compatible with image format. Assuming you're referring to a byte array, that's how you do it :

import os
import io
import Image
from array import array

def readimage(path):
    count = os.stat(path).st_size
    with open(path, "rb") as f:
        return bytearray(f.read())

bytes = readimage(path+extension)
image = Image.open(io.BytesIO(bytes))
image.save(savepath)

The code snippet was taken from here.

Hopefully this will help you, Yahli.

Community
  • 1
  • 1
Mr Yahli
  • 321
  • 2
  • 13
1

Here's an example that uses numpngw to create an image with a bit-depth of 1 (i.e. the values in the image are just 0s and 1s). The example is taken directly from the README file of the numpngw package:

import numpy as np
from numpngw import write_png

# Example 2
#
# Create a 1-bit grayscale image.

mask = np.zeros((48, 48), dtype=np.uint8)
mask[:2, :] = 1
mask[:, -2:] = 1
mask[4:6, :-4] = 1
mask[4:, -6:-4] = 1
mask[-16:, :16] = 1
mask[-32:-16, 16:32] = 1

write_png('example2.png', mask, bitdepth=1)

Here's the image:

png image

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214