我正在做一个项目,我需要连接很多图像 (80282)。每个图像都是 256 x 256 像素,有些文件是空的(没有图像),所以我需要创建一个空白图像来替换文件。我有这种格式的数据:data-D0H0-X52773-Y14041
X和Y对应我需要按顺序拼接的坐标。顺序是从左上X52773-Y14314到右下X52964-Y14041。它在 X 上有 294 次迭代,在 Y 上有 274 次迭代。这是我编写的代码,它无法正常工作,如果你有想法,我可以使用任何帮助,目前,我的图像在 Y 上没有很好地对齐。例如,图片 X10-Y10 不在图片 X10-Y11 的下方。我想我在正确使用 try: and except: 时遇到了一些问题 感谢您的帮助!
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 <= number <= 4294967295
不确定我的坐标计算是否正确。
代码:
from PIL import Image
import glob
import imghdr
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:6])
y_coord = int(tmp_arr[3][1:6])
info = imghdr.what(filename)
if (info == "png"):
new_img = Image.open(filename)
else:
new_img = Image.new('RGBA', (256,256))
x_coord = (x_coord-52672)*256
y_coord = (14314-y_coord)*256
print x_coord, y_coord
new_im.paste(new_img, (x_coord, y_coord))
new_im.show()
new_im.save('full_image.png')
请您参考如下方法:
您的坐标算法似乎有点不对劲。由于您的图像是 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')
