如何将转换命令更改为Python代码

5

我在项目中使用Imagemagick进行图像增强。由于我是一个Imagemagick的新手,所以我开始使用命令行参数来使用这个软件包。为了进一步处理,我需要将下面的命令转换成Python代码。

convert sample.jpg -blur 2x1 -sharpen 0x3 -sharpen 0x3 -quality 100 -morphology erode diamond -auto-orient -enhance -contrast -contrast-stretch 0 -gamma .45455 -unsharp 0.25x0.25+8+0.065 -fuzz 2% output.jpg

我认为可以使用wand包来实现。但是否可能将上述命令中使用的所有参数都转换一下呢?非常感谢您的帮助。谢谢。

尝试这里:https://dev59.com/AW445IYBdhLWcg3wia2V。相比于popen,os.system通常被认为不是一个好主意。 - joel goldstick
事实上,我无法继续使用那些选项(os.system和popen),因为我必须动态地上传要转换的图像。还有其他可用的选择吗? - Vijesh Venugopal
2个回答

4
你可以使用 os.system() 函数从 Python 中运行终端命令。
import os

command = 'convert sample.jpg -blur 2x1 -sharpen 0x3 -sharpen 0x3 -quality 100 -morphology erode diamond -auto-orient -enhance -contrast -contrast-stretch 0 -gamma .45455 -unsharp 0.25x0.25+8+0.065 -fuzz 2% output.jpg'

os.system(command)

如果你想动态使用路径,你也可以使用.format()方法:https://pyformat.info/

infile = 'sample.jpg'
outfile = 'output.jpg'

command = 'convert {} -blur 2x1 -sharpen 0x3 -sharpen 0x3 -quality 100 -morphology erode diamond -auto-orient -enhance -contrast -contrast-stretch 0 -gamma .45455 -unsharp 0.25x0.25+8+0.065 -fuzz 2% {}'.format(infile, outfile)

os.system(command)

谢谢您的回答。在这里,我们如何指定文件路径?在我的情况下,要转换的文件是动态上传的。 - Vijesh Venugopal
那很有道理。谢谢。 - Vijesh Venugopal

2

另一个选项是使用Wand,这是一个用于Python的ImageMagick绑定库,可以用它来转换上述命令。更多细节请参考以下链接:

wand文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接