2012-02-20 89 views
3

我希望能够使用PythonMagick生成蒙太奇。文档看起来很稀疏,但我一直试图使用Eclipse的代码完成部分来追捕它,以及其他一些关于Stack Overflow的问题。看来,MagickWand API有我要找的功能,可根据此:在Python 3中使用PythonMagick的蒙太奇?

http://www.imagemagick.org/api/MagickWand/montage_8c.html

不过,我似乎无法找到它在PythonMagick。这简直不可用吗?如果是这样的话,我可能会丢弃其余的PythonMagick代码,并依赖便携式ImageMagick发行版上的subprocess.call或类似的东西(该程序必须是可移植的,并且可以在Windows上运行,并带有一个简单的Mac OS端口...到目前为止,我还有其他一些PythonMagick命令可以工作,所以如果可能的话,我想让这条路线继续运行)。

谢谢!

回答

0

我有同样的问题,甚至pgmagick缺乏所需的montageImage()函数(Magick++ montage example

这是我做什么(在Django视图):

#ImageMagick CLI is better documented anyway (-background none preserves transparency) 
subprocess.call("montage -border 0 -geometry "+str(cols)+"x -tile 1x"+str(len(pages))+" "+target_path[0:len(target_path)-4]+"[0-9]*.png -background none "+target_path,shell=True)` 

不好玩,因为我有首先要处理一堆文件......写入硬盘并不是最快的事情,然后删除临时文件。

我宁愿这样做在公羊内。

我仍然在寻找更好的答案。

+0

检查我的回答在这个线程。你可能会觉得它很有用:) – 2015-04-25 18:13:52

1

使用python imagemagick/graphicsmagick绑定有很多帮助,但不幸的是并不是所有的功能都在那里。我实际上与@FizxMike有同样的问题。我需要使用蒙太奇,然后做一些进一步的操作,但将文件保存在硬盘上,然后将其重新加载到适当的pgmagick对象中,以便执行其余操作并再次保存它很慢。

最终我使用了子进程解决方案,但不是保存在文件中,而是将输出重定向到标准输出。然后,我使用stdout从pgmagick.Image对象中的pgmagick.Blob加载图像,并在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')