简体   繁体   中英

Pypng: numpy array differs from output PNG file

I'm trying to write a program that creates a png file and paints the outer pixel black. I only need black and white so bitdepth=1 works for my situation.

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

If I print the Maze to the console it looks fine:

[[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]]

The png.png file does not look like the numpy array

[[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 is black, 0 is white since I cant upload pictures)

I dont know why my console output is different from the png-file. I'm struggling to read the png-file. I know there is a read() method with a png.Reader but throws an Error: "png.FormatError: FormatError: PNG file has invalid signature."

Found my problem myself: instead of int i have to use unsigned bytes for the Image. Maze = np.ones((MazeHeight,MazeWidth),dtype=int) to Maze = np.ones((MazeHeight,MazeWidth),dtype=uint8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM