Pypng:numpy数组不同于输出的PNG文件

问题描述

我正在尝试编写一个程序,该程序创建png文件并将外部像素绘制为黑色。我只需要黑白即可,所以bitdepth = 1可以满足我的情况。

import png
import numpy as np 

MazeHeight = 5
MazeWidth = 7

if __name__ == "__main__":
    file = open('png.png','wb')
    writer = png.Writer(MazeWidth,MazeHeight,greyscale=True,bitdepth=1)
    #generating white array
    Maze = np.ones((MazeHeight,MazeWidth),dtype=int)
    #mark borders as black
    for i in range(MazeHeight):
        for j in range(MazeWidth):
            #top/bottom bordes
            if i == 0 or i == MazeHeight-1:
                Maze[i][j] = 0
            #left/right
            elif j == 0 or j == MazeWidth-1:
                Maze[i][j] = 0
    writer.write(file,Maze)
    file.close()

如果我将迷宫打印到控制台,看起来不错:

[[0 0 0 0 0 0 0]
 [0 1 1 1 1 1 0]
 [0 1 1 1 1 1 0]
 [0 1 1 1 1 1 0]
 [0 0 0 0 0 0 0]]

png.png文件看起来不像numpy数组

[[1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1]
 [0 1 1 1 0 1 1]
 [1 1 1 1 1 1 1]]

(1是黑色,0是白色,因为我无法上传图片

我不知道为什么我的控制台输出与png文件不同。我正在努力阅读png文件。我知道有一个带有png.Reader的read()方法,但是会引发错误:“ png.FormatError:FormatError:PNG文件具有无效的签名。”

解决方法

我自己发现了我的问题: 而不是int我必须对图像使用无符号字节。 Maze = np.ones((MazeHeight,MazeWidth),dtype=int)Maze = np.ones((MazeHeight,dtype=uint8)