0

I'm very new at this, so apologies for any term misuse.

I am coding in Python. I have a 2D list that contains the grayscale values for every pixel in an image. I have modified these values as needed and would now like to save them into a new image. How can I construct this new jpeg from my array of grayscale values?

I would like them saved in a manner that does not overwrite my original image files, if possible.

I am using PIL; I opened the original file with Image.open('filename') and extracted the grayscale values at each pixel location with im.getpixel((i,j)) inside two for loops.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93

2 Answers2

1

Something like this should get you going (not tested):

old_image = Image.open("old.jpg")
old_data = old_image.load()

new_image = Image.new("RGB", old_image.size)
new_data = new_image.load()

width, height = old_image.size
for x in range(width):
    for y in range(height):
        new_data[x, y] = old_data[x, y] 

new_image.save("new.jpg")
elyase
  • 39,479
  • 12
  • 112
  • 119
0

Careful with jpeg though, as jpeg will lose a lot of data. If you want to keep the values of each pixel without the loss from compression, then you should use png. See this question (which also has the answer to your original question in it) for more:

PIL changes pixel value when saving

Community
  • 1
  • 1
Schiem
  • 589
  • 3
  • 12