Indexerror: image index out of range using PIL

Asked

Viewed 200 times

0

I’m starting to work with image processing and need to do a simple exercise to double the size of a.

I have the following script:

from PIL import Image

imagem = Image.open("local_da_Imagem", "r")

largura, altura = imagem.size

fator = 2

W = largura
H = altura

nova_largura = int(largura*fator)
nova_altura = int(altura*fator)

nova_imagem = Image.new("RGB", (nova_largura, nova_altura))

for col in range(nova_largura):
  for row in range(nova_altura):
      p = imagem.getpixel((col, row))
      nova_imagem.putpixel((col*fator, row*fator), 100)

nova_imagem.show()

But when I run this script, I get the error: Indexerror: image index out of range.

Someone could help me. Showing me where I’m going wrong in this script?

I thank those who can.

1 answer

1


The two for are being traversed by nova_height and nova_width, which are the original height and width multiplied by 2, and you are using getPixel to pick up the image pixel at the position. That is, you are going through the image 2x its size, because you go through it with the values multiplied by 2. Besides, you are passing in putPixel the value 100, and not the value returned by getPixel. And according to the algorithm you gave me that the 0x0 would be in 0x1, 1x0, 1x1.

I arrived at something like this:

from PIL import Image

imagem = Image.open("Downloads/rgb.png", "r")

largura, altura = imagem.size

fator = 2

W = largura
H = altura

nova_largura = int(largura*fator)
nova_altura = int(altura*fator)

nova_imagem = Image.new("RGB", (nova_largura, nova_altura))

for col in range(largura):
  for row in range(altura):
      p = imagem.getpixel((col, row))
      nova_imagem.putpixel((col*fator, row*fator), p)
      nova_imagem.putpixel((col*fator+1, row*fator+1), p)
      nova_imagem.putpixel((col*fator+1, row*fator), p)
      nova_imagem.putpixel((col*fator, row*fator+1), p)


nova_imagem.show()
  • It would be possible an example of code correcting this error?

  • 1

    @Danilo Ai I can no longer help you, because I don’t know how the algorithm works, for example, the 0x0 pixel would be copied to where? 0x1? 1x0? 1x1? It would be in the 0x0 too, but it would have to be copied somewhere else for the image to increase in size.

  • Okay. No problem. But answer your question. For example, let’s say that the RGB value of my original image at position 0x0 is 1. To fold my image, I have to copy this value 1 to the following positions of the new image (0x0, 0x1, 1x0, 1x1).

  • 1

    @Danilo I edited and put a code, I don’t know if it’s totally right because I haven’t tested much, but it seems to present right.

  • Thank you very much @Vinicius Macelai. It’s working yes! Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.