Search code examples
pythonpngpython-imaging-librarylibpng

Creating a gray-scale image from an 2D array of pixel values


I am trying to change the values from a gray scale PNG image and then create an image from those changed values.

The first step I took was using a python implementation of libpng. With that I was able to get a list of all the pixel values of the PNG. It is a gray scale image so the values where from 0 to 100. I do a quick algorithm to change the values. And then I try to create it into a new PNG file. Its all on a single line so I use regex to format it into a 2D array.

I attempted to use this that I found here

from PIL import Image
import numpy as np


pixels = [[100,0,0],[0,100,0],[0,0,100]]
# Convert the pixels into an array using numpy
array = np.array(pixels)

print(array)

# Use PIL to create an image from the new array of pixels
new_image = Image.fromarray(array, 'L')
new_image.save('testing.png')

But I guess the formatting that PIL uses is different from what the libpng is so instead of making an image that looks like 3 white pixels diagonally, I only get 1 white pixel on the top left. So either I change the values I am getting from libpng so that numpy works, or I find something in libpng that will allow me to change the values directly and create the new file.


Solution

  • The error in your code is that you are not setting the right data type for the array. If you call array = np.array(pixels, dtype='uint8') then your code will work.