Python、ImageMagick 和 `subprocess`
我正在尝试通过一个Python脚本调用ImageMagick的montage
来合成图片,代码大概是这样的:
command = "montage"
args = "-tile {}x{} -geometry +0+0 \"*.png\" out.png".format( width, height)
sys.stdout.write( " {} {}\n".format(command, args) )
print subprocess.call( [command, args] )
但是,运行这个命令时,montage
只显示用法说明。如果我手动运行这个命令,一切都正常。ImageMagick在Windows上应该支持文件名通配符,所以像*.png这样的写法应该能正常工作。但看起来这个功能在subprocess
中被抑制了。我是不是需要使用glob
来给montage
提供一个文件名的列表呢?
进一步的信息
谢谢你的帮助。不过即使我使用:
command = "montage"
tile = "-tile {}x{}".format( width, height)
geometry = "-geometry +0+0"
infile = "*.png"
outfile = "out.png"
sys.stdout.write( " {} {} {} {} {}\n".format(command, tile, geometry, infile, outfile) )
print [command, tile, geometry, infile, outfile]
#~ print subprocess.call( [command, tile, geometry, infile, outfile] )
print subprocess.call( ['montage', '-tile 9x6', '-geometry +0+0', '*.png', 'out.png'] )
我还是遇到了一个错误:
Magick: unrecognized option `-tile 9x6' @ error/montage.c/MontageImageCommand/1631.
我使用的是Windows 7,ImageMagick版本是6.6.5-7,发布时间是2010年11月5日,Q16,Python版本是2.7。
3 个回答
0
subprocess.call
这个函数需要你把整个命令分成一个列表,也就是说每个参数要单独放在列表的一个元素里。你可以试试这样做:
import shlex
command = "montage"
args = "-tile {}x{} -geometry +0+0 \"*.png\" out.png".format( width, height)
subprocess.call( shlex.split('{} {}'.format(command, args)) )
3
jd已经给你解决方案了,不过你没有仔细看哦;)
这个是错误的:
subprocess.call( ['montage', '-tile 9x6', '-geometry +0+0', '*.png', 'out.png'] )
这个是正确的:
subprocess.call( ['montage', '-tile', '9x6', '-geometry', '+0+0', '*.png', 'out.png'] )
5
你应该把第一个参数改成 ['montage', '-tile', '{}x{}'.format(...), '-geometry'...]
,而不是 [command, args]
。你可能还需要加上 shell=True
。