How to read a grayscale image in Python using pypng

what we start with is to include like this:

[code lang="python"]import[/code]

with we wil now open a png reader from a specified path and then just interate through each pixel, with grayscale you just read one color value, we can ignore the other values such as green and blue as all color should be at the same scale. I have notice slight fluctuations in the values, but that just depends on how your image editor saves the file.

here is my code:

[code lang="python"]
reader = png.Reader(os.path.join(os.path.dirname(__file__), 'static', 'earth.png') ) # streams are also accepted
    w, h, pixels, metadata =
    pixel_byte_width =  4 if metadata['has_alpha'] else 3

    fov =  2# fov is how many tiles a unit can see around it
    xleft = max(unit.x - fov, 0)
    xright = min(unit.x + fov + 1, w)
    ytop = max(unit.y - fov, 0)
    ybottom = min(unit.y + fov + 1, h)

    for x in range(xleft, xright):
        for y in range(ytop, ybottom):

            pixel_position = (y * w) + x

            pixel = pixels[
              pixel_position * pixel_byte_width :
              (pixel_position + 1) * pixel_byte_width]

            alt = pixel[1]


Comments are closed.