如何合并100张图像以获得大图像?

时间:2018-10-23 13:49:31

标签: python image python-imaging-library bioinformatics

enter image description here

合并100张图片时遇到了一些问题,因此它们可以像上面那样构建10 x 10的大图片:我尝试这样做:

from PIL import Image
image1 = Image.open("4XP6edit.png")
image2 = Image.open('4MBSedit.png')
(width, height) = image1.size
result_width = 10*width
result_height = 10*height

result = Image.new('RGB', (result_width, result_height))
result.paste(im=image1, box=(0, 0))
result.paste(im=image2, box=(width, 0))
result.paste(im=image2, box=(2*width, 0))
# and so on until 10*width, 0 and than:
result.paste(im=image10, box=(0, height))
result.paste(im=image10, box=(0, 2*height))

这工作正常,但是我希望它可以在for循环或sth中自动创建。但是我的建议没有用。有人能找到我的错误吗?

length = len(protein_list)
k=0; m=0; j=0

for i in range(length):
    image= Image.open(str(protein_list[i] + 'edit.png')

    (width, height) = image.size

    result_width = 10*width 
    result_height = 10*height

    result = Image.new('RGB', (result_width, result_height))
    if (k == 10): k = 0
    if (j >= 0 and j <= 9):  m = 0
    if (j >= 10 and j <= 19):  m = 1
    if (j >= 20 and j <= 29): m = 2
    if (j >= 30 and j <= 39): m = 3
    if (j >= 40 and j <= 49): m = 4    
    if (j >= 50 and j <= 59): m = 5
    if (j >= 60 and j <= 69): m = 6    
    if (j >= 70 and j <= 79): m = 7
    if (j >= 80 and j <= 89): m = 8
    if (j >= 90 and j <= 99): m = 9    

    result.paste(im=image, box=(k*width, m*height))
    k= k+1
    j=j+1


result

我知道这是否真的很丑,但是我是编程新手,所以请原谅。.有人可以帮我吗? 它显示了一张巨大的10x10黑色图片,其中显示了proteinedit.png的一张图片。 看起来像这样 enter image description here

1 个答案:

答案 0 :(得分:3)

之所以这样,是因为您在循环的每次迭代中都定义了结果图像。 如果所有图像大小均相同,则可以执行以下操作:

length = len(protein_list)
k=0; m=0; j=0
result = None

    for i in range(length):
        image= Image.open(str(protein_list[i] + 'edit.png')
        if result is None:
            (width, height) = image.size

            result_width = 10*width 
            result_height = 10*height

            result = Image.new('RGB', (result_width, result_height))

    if (k == 10): k = 0
    ...

result

其余的代码可以使用很多改进,因此,如果可行,我会将其带到Code Review SO。