无法打开图片。目前不支持有效的位图文件或其格式

时间:2017-05-06 16:26:51

标签: python python-2.7 numpy bitmap pypng

我编写了这个Python程序来创建矩阵(2D数组)并将其保存到.png文件中。该程序编译并运行没有任何错误。甚至创建了IMAGE.png文件,但png文件仍然无法打开。当我尝试在MSpaint中打开它时,它说:

  

无法打开图片。目前不支持有效的位图文件或其格式。

源代码:

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();

由于没有错误消息,我不明白我哪里出错了。请帮助。

PS-我只想将矩阵保存为图像文件,所以如果你有更好更简单的方法在Python2.7中做,请做一下建议。

谢谢。

2 个答案:

答案 0 :(得分:1)

并非每个阵列都与图像格式兼容。假设你指的是一个字节数组,那你就是这样做的:

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)

代码段取自here

希望这会对你有所帮助, Yahli。

答案 1 :(得分:1)

这是一个使用numpngw创建比特深度为1的图像的示例(即图像中的值只是0和1)。该示例直接取自numpngw包的README文件:

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)

这是图像:

png image

相关问题