简体   繁体   English

在PIL Python中合并和保存图像

[英]Merging and saving images in PIL Python

I have two folders of images and I am trying to build one large image from all the slices in each folder. 我有两个文件夹的图像,我试图从每个文件夹中的所有切片中构建一个大图像。 I need to alternate between folders to build the image. 我需要在文件夹之间交替以生成图像。 For example the first slice comes from folder 1, the second slice comes from folder 2, the third from folder 1 ect. 例如,第一个切片来自文件夹1,第二个切片来自文件夹2,第三个切片来自文件夹1等。 I have the files ordered by filename in the individual folders so I am trying to iterate through the folders and add a new strip to an image. 我在各个文件夹中按文件名对文件进行了排序,因此我试图遍历这些文件夹并向图像添加新的条带。 The code runs BUT it doesn't seem to be saving the composite image. 该代码运行,但它似乎并没有保存合成图像。 I am new to PIL, so I am sure that it is something simple, but your help is appreciated. 我是PIL的新手,所以我相信这很简单,但是感谢您的帮助。 Thanks! 谢谢!

def merge_images(file1, file2):
   """Merge two images into one, displayed above and below
   :param file1: path to first image file
   :param file2: path to second image file
   :return: the merged Image object
   """

   if file1.startswith('.'):
       return None

   image1 = Image.open(file1)
   image2 = Image.open(file2)

   (width1, height1) = image1.size
   (width2, height2) = image2.size

   result_width = width1 + width2
   result_height = max(height1, height2)

   result = Image.new('RGB', (result_width, result_height))
   result.paste(im=image1, box=(0, 0))
   result.paste(im=image2, box=(0, height1))

   return result

imageCounter = 0
firstPass = True
compImage = Image.new('RGBA', img.size, (0,0,0,0))

for i in range(len(boundingBoxes)+1):
    if firstPass:
        compImage = merge_images('./image_processing/'+ os.listdir('./image_processing/')[imageCounter],
        './img_patches/outputs/'+os.listdir('./img_patches/outputs/')[imageCounter])


        if compImage is not None:
            firstPass = False

            compImage.save('./image_processing/compImage.jpg')


    else:
        compImage = merge_images('./image_processing/compImage.jpg','./image_processing/'+ os.listdir('./image_processing/')[imageCounter])

        compImage.save('./image_processing/compImage.jpg')
        compImage = merge_images('./image_processing/compImage.jpg','./img_patches/outputs/'+ os.listdir('./img_patches/outputs/')[imageCounter])

        compImage.save('./image_processing/compImage.jpg')

    imageCounter = imageCounter + 1

You have to tell PIL to save the images: 您必须告诉PIL保存图像:

for i in range(len(boundingBoxes)+1):
    if firstPass:
        compImage = merge_images('./image_processing/'+ os.listdir('./image_processing/')[imageCounter],
        './img_patches/outputs/'+os.listdir('./img_patches/outputs/')[imageCounter])
        compImage.save(open('output/{}.png'.format(imageCounter), 'w'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM