Использование привязок python imagemagick/graphicsmagick помогает много, но, к сожалению, не все функциональные возможности еще есть. У меня на самом деле была такая же проблема с @FizxMike. Мне нужно было использовать монтаж, а затем выполнить некоторые дополнительные операции, но сохранить файл на жестком диске, а затем перезагрузить его в правильном объекте pgmagick, чтобы выполнить остальные операции и сохранить его снова, было медленным.
В конце концов я использовал решение подпроцесса, но вместо сохранения в файле я перенаправляю вывод в stdout. Затем я использую stdout для загрузки изображения из pgmagick.Blob в объект pgmagick.Image и выполняю остальную часть обработки в коде python.
Процедура выглядит в коде:
import os
import pgmagick
import subprocess
my_files = []
# Dir with the images that you want to operate on
dir_with_images = "."
for file in os.listdir(dir_with_images):
if file.endswith(".png"):
my_files.append(os.path.join(dir_with_images, file))
montage_cmd = ['gm', 'montage']
montage_cmd.extend(my_files)
# The trick is in the next line of code. Instead of saving in a file, e.g. myimage.png
# the montaged file will just be "printed" in the stdout with 'png:-'
montage_cmd.extend(['-tile', '2x2', '-background', 'none', '-geometry', '+0+0', 'png:-'])
# Use the command line 'gm montage' since there are not python bindings for it :(
p = subprocess.Popen(montage_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Get the stdout in a variable
stdout, stderr = p.communicate()
# Load the stdout in a python pgmagick Image object using the pgmagick.Blob
# and do the rest of the editing on python code
img = pgmagick.Image(pgmagick.Blob(stdout))
# Display the image
img.display()
geometry = pgmagick.Geometry(300, 200)
geometry.aspect(True)
# Resize the montaged image to 300x200, but keep the aspect ratio
img.scale(geometry)
# Display it again
img.display()
# And finally save it <- Only once disk access at this point.
img.write('myimage.png')
Проверьте свой ответ в этой теме. Вы можете найти это полезным :) –