如何提取具有给定宽高比的居中,裁剪的内部图像部分

时间:2018-01-04 22:21:38

标签: imagemagick

在下图中,蓝色矩形表示任意源图像。对于每个图像,我想提取一个

的部分(以红色显示)
  • 指定的宽高比(在本例中,它们都是3:2)
  • 在源图像中拟合时尽可能大
  • 以源图片为中心

如何使用ImageMagick命令行工具执行此操作?

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用如下命令从图像中心裁剪最大可能的3:2部分......

convert input.png \
   -set option:distort:viewport "%[fx:(w/3)<(h/2)?w:h*3/2]x%[fx:(w/3)<(h/2)?w*2/3:h]" \
   \( xc: -distort SRT 0 \) +swap -gravity center -composite output.png

使用输入图像的尺寸来计算输出图像的大小,将这些尺寸的空白图像创建为一种模板,然后合成以该模板为中心的输入图像。结果基本上是从输入中心裁剪出的3:2图像。

编辑添加...

这是另一种方法,它只是重置页面信息以指定新的画布尺寸和偏移,然后在新画布中正确地展平图像。

convert input.png \
   -set page "%[fx:(w/3)<(h/2)?w:h*3/2]x%[fx:(w/3)<(h/2)?w*2/3:h]" \
   -set page "-%[fx:(w/3)<(h/2)?0:(w-(h*3/2))/2]-%[fx:(w/3)<(h/2)?(h-(w*2/3))/2:0]" \
   -flatten output.png

这不需要创建模板图像或进行复合操作,在测试中它似乎比我上面的其他建议快得多。

答案 1 :(得分:0)

如果您只想要具有w>h方面的水平裁剪,那么您可以在Unix语法中按照以下方式在ImageMagick 6中执行此操作:

输入:

enter image description here

infile="monet2.jpg"
aspect="3:2"
ww=`convert -ping "$infile" -format "%w" info:`
hh=`convert -ping "$infile" -format "%h" info:`
ratio=`convert xc: -format "%[fx:$ww/$hh]" info:`
aspect1=`echo $aspect | cut -d\: -f1`
aspect2=`echo $aspect | cut -d\: -f2`
aspect=`convert xc: -format "%[fx:$aspect1/$aspect2]" info:`
test=`convert xc: -format "%[fx:$aspect>=$ratio?1:0]" info:`
if [ $test -eq 1 ]; then
    width=$ww
    height=`convert xc: -format "%[fx:$hh*$ratio/$aspect]" info:`
else
    width=`convert xc: -format "%[fx:$ww*$aspect/$ratio]" info:`
    height=$hh
fi  
convert "$infile" -gravity center -crop ${width}x${height}+0+0 +repage result.jpg

enter image description here

输入:

enter image description here

infile="barn.jpg"
aspect="3:2"
ww=`convert -ping "$infile" -format "%w" info:`
hh=`convert -ping "$infile" -format "%h" info:`
ratio=`convert xc: -format "%[fx:$ww/$hh]" info:`
aspect1=`echo $aspect | cut -d\: -f1`
aspect2=`echo $aspect | cut -d\: -f2`
aspect=`convert xc: -format "%[fx:$aspect1/$aspect2]" info:`
test=`convert xc: -format "%[fx:$aspect>=$ratio?1:0]" info:`
if [ $test -eq 1 ]; then
    width=$ww
    height=`convert xc: -format "%[fx:$hh*$ratio/$aspect]" info:`
else
    width=`convert xc: -format "%[fx:$ww*$aspect/$ratio]" info:`
    height=$hh
fi  
convert "$infile" -gravity center -crop ${width}x${height}+0+0 +repage result2.jpg

enter image description here

如果在类Unix操作系统上,请参阅我的脚本,aspectcrop,http://www.fmwconcepts.com/imagemagick/index.html

如果您提供w<h方面,则相同的代码将垂直裁剪。

在ImageMagick 7中,如果您将方面提供为分数而不是冒号分隔比率,则可以在一个命令行中执行此操作:

infile="monet2.jpg"
aspect="1.5"
magick "$infile" \
-gravity center \
-crop "%[fx:$aspect>=(w/h)?w:w*$aspect/(w/h)]x%[fx:$aspect>=(w/h)?h*(w/h)/$aspect:h]+0+0" \
+repage \
result.jpg