0

I am trying to change the value of the pixels of an image using Image from PIL library. As you can see in my code the first thing i do is load the image and convert it to a gray scale. Next I get the data of the pixels and load it to a list and normalize that list. After that i read again the list and make the changes with the conditions i need, but now i dont know how to apply this changes to the images. What should I do? from PIL import Image

img_path = "image01.png"
img = Image.open(img_path).convert('L')

pixel_values = list(img.getdata())

print(pixel_values[10:15])

# Normalizamos la imagen
for i in range(len(pixel_values)):
    pixel_values[i] = pixel_values[i]/255

print(pixel_values[10:15])

# Modificamos los valores de los pixeles (blanco = 1 y negro = 0)
max_black = 0.05
for i in range(len(pixel_values)):
    if pixel_values[i] <= max_black:
        pixel_values[i] = 0
    else:
        pixel_values[i] = 1

print(pixel_values[10:15])

# Update
img2 = Image.new('L', img.size)
img2.putdata(pixel_values)
img2.save(".\\prueba_2\\image01_new.png")
  • Have you tried using `img.save()`? – B Remmelzwaal Feb 21 '23 at 11:35
  • @BRemmelzwaal yes i have tried it and the image that is saved is the same as the one in the start –  Feb 21 '23 at 11:42
  • 1
    I see what's going on now. You're getting the pixel values but those are now disjoint from the actual PIL image. Try doing `im2 = Image.new(im.mode, im.size); im2.putdata(pixel_values)` and save that, or overwrite the original image using `im.putdata(pixel_values)`. Found [here](https://stackoverflow.com/a/12063264/17200348). – B Remmelzwaal Feb 21 '23 at 11:45
  • @BRemmelzwaal done, but the im2 is just a black image and not what the pixel_values show if the are shown as list –  Feb 21 '23 at 11:52
  • You really should try to avoid treating images as lists and processing them with `for` loops - it is slow, error-prone and inefficient. Try to use built-in functions from PIL that are written in `C` or Numpy operations. You are merely thresholding the image which you can do with `Image.point()`. – Mark Setchell Feb 21 '23 at 11:56
  • @MarkSetchell how do i do that, i´m quite new whith PIL –  Feb 21 '23 at 11:58
  • There’s something very close to it here https://stackoverflow.com/a/56913182/2836621 – Mark Setchell Feb 21 '23 at 12:28

0 Answers0