使用 ImageMagick 和一些 bash shell 脚本,这是计算它的方法。
使用基本点旋转方程。 (见https://en.wikipedia.org/wiki/Rotation_of_axes)。但是,由于旋转是围绕中心进行的,因此必须从点坐标中减去输入的中心坐标,进行旋转,然后将输出图像的中心加回去。
注意 ImageMagick 的旋转是顺时针的,而通常的坐标变换方程是逆时针的。所以我必须否定旋转角度。
还要注意,Y 在图像坐标中向下为正,而法线坐标旋转的 Y 向上。因此,图像和正常笛卡尔坐标系之间的方程中存在符号交换。
这是我创建的测试图像:
convert -size 300x300 xc:skyblue -size 100x100 xc:pink -geometry +50+50 -composite test.png
很明显(来自 ImageMagick 命令),四个角是:
pt1=50,50
pt2=149,50
pt3=149,149
pt4=59,149
较大的值 (149) 比粉红色尺寸加上起始坐标 (100-1+50=149) 小 1,因为 ImageMagick 中的索引从 0 开始。偏移量相对于 0。
接下来我旋转图像:
convert test.png -background black -rotate 20 test2.png
所以要计算输出中的 4 个点,我首先需要知道对于给定的旋转角度输出有多大。
angle=20
ww=300
hh=300
ang=-$angle
wwr=$(convert xc: -format "%[fx:($ww*cos(pi*abs($ang)/180)+$hh*sin(pi*abs($ang)/180))]" info:)
hhr=$(convert xc: -format "%[fx:($ww*sin(pi*abs($ang)/180)+$hh*cos(pi*abs($ang)/180))]" info:)
echo "$wwr x $hhr"
384.514 x 384.514
Rounding to whole numbers, it would be
wwr=385
hhr=385
Note for computing the new dimensions, I use the abs of the sin and cos and all positive signs
接下来,我将这 4 个点重新格式化为 X 和 Y 数组,以便稍后处理。
pt1=50,50
pt2=149,50
pt3=149,149
pt4=59,149
list="$pt1 $pt2 $pt3 $pt4"
echo "$list"
i=0
for pt in $list; do
xArr[$i]=$(echo "$pt" | cut -d, -f1)
yArr[$i]=$(echo "$pt" | cut -d, -f2)
i=$((i+1))
done
echo "${xArr[*]}"
50 149 149 59
echo "${yArr[*]}"
50 50 149 149
现在,我计算旋转的 4 个角坐标:
angle=20
xlast=299
ylast=299
wwr=385
hhr=385
for ((i=0; i<4; i++)); do
xr=$(convert xc: -format "%[fx:((${xArr[$i]}-300/2)*cos(pi*$ang/180)+(${yArr[$i]}-300/2)*sin(pi*$ang/180)) + $wwr/2]" info:)
yr=$(convert xc: -format "%[fx:((${yArr[$i]}-300/2)*cos(pi*$ang/180)-(${xArr[$i]}-300/2)*sin(pi*$ang/180)) + $hhr/2]" info:)
echo "$xr,$yr"
done
132.733,64.3287
225.762,98.1887
191.902,191.218
107.33,160.436
您可以在输出图像中测量它们以查看它们是否正确。您可以根据需要四舍五入到整数。
如果您想要矩形边界框,则只需计算 minx、miny、maxx、maxy 值。