0
我有兩個圖像文件夾,我試圖從每個文件夾中的所有切片構建一個大圖像。我需要在文件夾之間交替來構建圖像。例如,第一個切片來自文件夾1,第二個切片來自文件夾2,第三個來自文件夾1等。我有單個文件夾中按文件名排序的文件,所以我試圖遍歷文件夾併爲圖像添加一個新條。代碼運行,但它似乎並沒有保存複合圖像。我是PIL新手,所以我確信這很簡單,但您的幫助表示感謝。謝謝!在PIL中合併並保存圖像Python
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
@miltonjbradley,只是不爲他們節省在所有實際。 –