我需要一种快速可靠的方法来修改大量图像。我想去除图片周围有很多白色。问题是,这是一些相似的图片,但它们的大小不同。以下是一个例子:一条链接我的图片只有红色和蓝色部分,周围有一大片空白。我想要格式相同、空白较少的图片。
首先我需要所有图片中非白色部分的最大尺寸,然后将所有图片裁剪为最大尺寸的格式。但图像的中心必须保持在中心。
这是否可以通过转换或任何其他命令行工具实现?
答案1
好吧,经过一个小时的谷歌搜索,我找到了自己的解决方案。此链接有一个脚本可以遍历所有图片并裁剪它们,同时中心保持在中心。现在我有了裁剪后的图片。使用
ww=`convert -ping "$f" -format "%w" info:
循环遍历所有图片的所有 ww 值,我得到了 wmax。
wmax=`convert xc: -format "%[fx:max($ww,$wmax)]" info:`
通过这个和几个循环
convert $f -gravity center -background white -extent ${wmax}x${hmax} ${f}-canvas.png
我得到了结果。结果并不好,我比需要的裁剪次数多一次,但它完成了工作,我必须完成我的论文。
#!/bin/sh
# gives the largest x and y values of all png files in directory and puts them in the center of a canvas. This canvas is 10px*10px larger than the largest png file.
# We cycle over all pngs to get maximum w and h
for f in *.png
do
echo "Processing $f file..."
# take action on each file. $f has current file name
wmax=0
hmax=0
# width
ww=`convert -ping "$f" -format "%w" info:`
#echo $ww
# height
hh=`convert -ping "$f" -format "%h" info:`
#echo $hh
wmax=`convert xc: -format "%[fx:max($ww,$wmax)]" info:`
hmax=`convert xc: -format "%[fx:max($hh,$hmax)]" info:`
# centertrim $f
# rm $f
# mv $f.out $f
done
echo $wmax
echo $hmax
wmaxp10=$(($wmax + 10 ))
echo $wmaxp10
hmaxp10=$(($hmax + 10 ))
echo $hmaxh10
# now we cycle through all pictures and add them to a canvas with $wmax+10 $hmax+10
for f in *.png
do
echo "Processing $f file..."
# take action on each file. $f has current file name
echo convert $f -gravity center -background white -extent ${wmaxp10}x${hmaxp10} ${f}-canvas.png
convert $f -gravity center -background white -extent ${wmaxp10}x${hmaxp10} ${f}-canvas.png
# centertrim $f
# rm $f
# mv $f.out $f
done
答案2
尝试以下 bash 脚本:
#!/bin/bash
max_width=0
max_height=0
border=10
# Trim all files to remove the white borders
for i in *.png; do
convert $i -trim "${i%.*}"__trimmed.png
done
# Find the max width and height
for i in *__trimmed.png; do
w="$(identify -format "%w" $i)"
h="$(identify -format "%h" $i)"
if (( $w > $max_width )); then max_width=$w; fi;
if (( $h > $max_height )); then max_height=$h; fi;
done
# Add a small border (optional)
max_width=$(($max_width+$border))
max_height=$(($max_height+$border))
# Add borders to all pictures so that they all have the same size
# "-gravity center" will center them
# -background None will avoid the default white background as your sample image
# was a png with a transparent backgroud
for i in *__trimmed.png; do
convert $i -background None -gravity center -extent "${max_width}x${max_height}" "${i%__trimmed.*}".png
done
rm -f *__trimmed.png