2014-10-08 56 views
-1

我的目的是做如下所示:如何翻译python PIL中的图像?

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

My功能:

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") 

出现此错误:

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 

过程,退出代码完成1

回答

0

您正在迭代x和y但改变它每一次迭代中:在范围

为Y(0,高度):

for x in range(0, width): 

    xy = (x, y)  
    red, green, blue = destino.getpixel(xy)  
    x += x_loc #this changes the value of x 
    y += y_loc #this changes the value of y 

    #at this point x can be outside of 0..height-1 and y can be outside of 0..width-1 
    destino.putpixel((x, y), (red, green, blue)) 

你可以尝试迭代:

for y in range(0,height-yloc): 
    for x in range(0,height-xloc): 
     xy = (x, y)  
     red, green, blue = destino.getpixel(xy)  
     x += x_loc 
     y += y_loc 
     #at this point x can be outside of 0..height-1 and y can be outside of 0..width-1 
     destino.putpixel((x, y), (red, green, blue)) 

BTW范围(0,A)可写成范围(a)

另外,这两个命令没有做任何事情,因为你没有将它分配给任何变量:

imagem1.convert("RGB") 
destino.convert("RGB") 
+0

好点,但不是错误消息的来源。 – 2014-10-08 04:03:31

+0

问题在于x和y正在被翻译,并且在翻译之后落在图像之外。 – carlosdc 2014-10-08 04:13:10

0

我的同事设法解决了这个问题。解决方案如下:

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")