How to translate an image in python?

Asked

Viewed 500 times

2

My intention is to do as in the figure below:

http://postimg.org/image/pdb6urf1d/

My job:

def translacao(imagem1):
    imagem1.save("translate.png")
    destino = Image.open("translate.png")
    destino = destino.resize((400,400))
    #Tamanho Imagem - Largura e Altura
    width = destino.size[0]
    height = destino.size[1]
    x_loc = 20
    y_loc = 20
    x_loc = int(x_loc)
    y_loc = int(y_loc)
    imagem1.convert("RGB")
    destino.convert("RGB")
    for y in range(0, height):
        for x in range(0, width):
             xy = (x, y)
             red, green, blue = destino.getpixel(xy)
             x += x_loc
             y += y_loc
            destino.putpixel((x, y), (red, green, blue))

    return destino.save("translate.png")

This error appears:

  C:\Python27\python.exe C:/Users/Mikhail/PycharmProjects/SistMult/histograma.py
  Traceback (most recent call last):
  File "C:/Users/Mikhail/PycharmProjects/SistMult/histograma.py", line 289, in <module>
  translacao(imagem1)
  File "C:/Users/Mikhail/PycharmProjects/SistMult/histograma.py", line 262, in translacao
  destino.putpixel((x, y), (red, green, blue))
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1269, in putpixel
  return self.im.putpixel(xy, value)
  IndexError: image index out of range

  Process finished with exit code 1
  • The error says that you are exceeding the image limit, it has 400x400 and at a certain point of the for vc is putting +20 going to 401, 402... 420, trying to put pixel beyond the limit.

  • What I change in code to do Image Translation?

1 answer

2

My colleague managed to solve the problem. Solution just below:

destino = Image.open("foto.png")
      #Tamanho Imagem - Largura e Altura
      lar = destino.size[0]
      alt = destino.size[1]
      x_loc = 200
      y_loc = 200
      imagem_original = np.asarray(destino.convert('RGB'))
      for x in range(lar):
           for y in range(alt):
                if x >= x_loc and y >= y_loc:
                     yo = x - x_loc
                     xo = y - y_loc
                     destino.putpixel((x,y), (imagem_original[xo,yo][0],imagem_original[xo,yo][1],imagem_original[xo,yo][2]))
                else:
                     destino.putpixel((x,y), (255, 255, 255, 255))
      destino.save("translate.png")

Browser other questions tagged

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