Python PIL连接图像
我正在做一个项目,我需要连接很多图像(80282)。每个图像是256 x 256像素,并且一些文件是空的(没有图像),因此我需要创建一个空白图像来替换该文件。我有以下格式的数据:data-D0H0-X52773-Y14041 X和Y对应于我需要按顺序连接的坐标。顺序是从左上角的X52773-Y14314到右下角的X52964-Y14041。X轴上有294次迭代,Y轴上有274次迭代。这是我编写的代码,工作不正常。如果您有任何想法,我可以使用任何帮助。目前,我的图像在Y轴上没有很好地对齐。例如,图像X10-Y10不在图像X10-Y11下。我想我在正确使用try:时遇到了一些问题,除了: 谢谢你的帮助Python PIL连接图像,python,image,python-imaging-library,Python,Image,Python Imaging Library,我正在做一个项目,我需要连接很多图像(80282)。每个图像是256 x 256像素,并且一些文件是空的(没有图像),因此我需要创建一个空白图像来替换该文件。我有以下格式的数据:data-D0H0-X52773-Y14041 X和Y对应于我需要按顺序连接的坐标。顺序是从左上角的X52773-Y14314到右下角的X52964-Y14041。X轴上有294次迭代,Y轴上有274次迭代。这是我编写的代码,工作不正常。如果您有任何想法,我可以使用任何帮助。目前,我的图像在Y轴上没有很好地对齐。例如,图
from PIL import Image
width = 75264
height = 70144
new_im = Image.new('RGBA', (75264, 70144))
x_offset = 0
y_offset = 0
coordinate = {}
coordinate['x']=52672
coordinate['y']=14314
#top image line should be from: X52,672-Y14,314 to X52,965-Y14,314
#bottom image line should be from: X52,672-Y14,041 to X52,965-Y14,041
for irow in range(0, 274):
for icol in range(0, 294):
try:
if (x_offset == width):
coordinate['y'] = coordinate['y'] - 1
coordinate['x'] = 52672
img = Image.open("data-D0H0-X"+str(coordinate['x'])+"-Y"+str(coordinate['y'])+".png")
except:
coordinate['x'] = coordinate['x'] + 1
blank = Image.new('RGBA', (256,256))
new_im.paste(blank, (x_offset, y_offset))
x_offset += 256
if (x_offset == width):
x_offset = 0
y_offset += 256
break
new_im.paste(img, (x_offset, y_offset))
x_offset += 256
if (x_offset == width):
x_offset = 0
y_offset += 256
coordinate['x'] = coordinate['x'] + 1
new_im.show()
new_im.save('full_image.png')
编辑:
这是我根据你的答案修改的新代码。但是,我仍然得到一个错误:
struct.error:“I”格式需要0您的坐标算法似乎有点不正确。由于您的图像是256x256,因此您不必像在代码中那样将x和y的进位/进位为1。 下面的代码还没有经过测试,但应该提供一个概要
from PIL import Image
import glob
width = 75264
height = 70144
new_im = Image.new('RGBA', (width, height))
for filename in glob.glob('data-D0H0-X*.png'):
tmp_arr = filename.split('-')
x_coord = int(tmp_arr[2][1:])
y_coord = int(tmp_arr[3][1:])
small_img = Image.open(filename)
new_im.paste(small_img, (x_coord, y_coord))
new_im.show()
new_im.save('full_image.png')
嗨,谢谢你的回答,它帮助了我!我还有一个问题,当我的文件里没有任何东西的时候,我怎么能有一个白色的图像呢?目前,代码显示:IOError:当涉及到没有数据的文件时,无法识别图像文件“data-D0H0-X52673-Y14072.png”。好的,您可以事先清除空文件,或者添加一个检查来忽略循环中大小为零的文件:import os;对于glob.glob('data-D0H0-X*.png')中的文件名:if os.stat(filename).st_size!=0:…您好,我找到了使用“imghdr.what()”检查文件的方法。为了你的帮助,我编辑了我的第一篇文章。我仍然收到一个错误,你知道我如何解决它吗?为什么在文件名中已经有了正确的坐标时,你要将所有的值乘以256?文件名中的坐标在X上是从52672到52965,在Y上是从14314到14041。而不是从0到新图像的宽度/长度,那么,它如何将其粘贴到原始坐标的正确位置呢?我想我们必须指明粘贴的位置。像素图像的宽度/长度从0到创建图像的宽度/长度(image.new('RGBA',(宽度,高度)))是否有问题?
from PIL import Image
import glob
width = 75264
height = 70144
new_im = Image.new('RGBA', (width, height))
for filename in glob.glob('data-D0H0-X*.png'):
tmp_arr = filename.split('-')
x_coord = int(tmp_arr[2][1:])
y_coord = int(tmp_arr[3][1:])
small_img = Image.open(filename)
new_im.paste(small_img, (x_coord, y_coord))
new_im.show()
new_im.save('full_image.png')