凸包是包含一組點集中所有點的最小面積凸多邊形。凸包可以被視為將橡皮筋拉伸到一組點周圍所包圍的形狀。
凸包字串格式返回包含所有非黑色像素的凸包多邊形頂點的 x,y 坐標列表。
magick [-fuzz value%] [-background background-color] -format "%[convex-hull]" info:
使用 %[convex-hull:extreme-points] 只返回頂部、右側、底部和左側的極值點。
其中,字串格式對可選的 -fuzz 值和由定義指定的可選背景顏色敏感。除非定義了背景顏色,否則上述命令將根據模糊值自動找到背景顏色。未指定時,模糊值的預設值為 0。
例如,考慮以下黑色背景上的白色矩形
![[Convex Hull]](/script/../image/convex-hull.png)
凸包點集可以計算為
magick rect.png -format "%[convex-hull]" info: 190,121 193,122 281,154 377,189 378,190 377,193 345,281 310,377 309,378 306,377 218,345 122,310 121,309 122,306 154,218 189,122 190,121
也可以使用 -draw 將凸包繪製為多邊形(填充或未填充),如下所示
magick rect.png -set option:hull "%[convex-hull]" -fill none -stroke red -strokewidth 1 -draw "polygon %[hull]" blocks_hull.png
以下是在黑色背景上使用非凸形狀圖像的示例
![[Convex Hull Blocks]](/script/../image/convex-hull-blocks.png)
magick blocks_black.png -set option:hull "%[convex-hull]" -fill none -stroke red -strokewidth 1 -draw "polygon %[hull]" blocks_hull.png
![[Convex Hull Blocks Closure]](/script/../image/convex-hull-blocks-closure.png)
最後,以下是一個使用 -fuzz 確定非恆定、非黑色背景的背景顏色的示例
![[Convex Hull Barn]](/script/../image/convex-hull-barn.jpg)
現在讓我們突出顯示圖像前景對象的凸包
magick barn_rot20.png -fuzz 10% -set hull "%[convex-hull]" -fill none -stroke red -strokewidth 1 -draw "polygon %[hull]" barn_rot20_hull.png
![[Convex Hull Barn Closure]](/script/../image/convex-hull-barn-closure.jpg)
最小邊界框
與圖像前景對象的凸包類似,是其最小邊界框。使用 %[minimum-bounding-box] 返回構成邊界框的點。此外,還會設定以下屬性:minimum-bounding-box:area、minimum-bounding-box:width、minimum-bounding-box:height 和 minimum-bounding-box:angle。
magick barn_rot20.png -fuzz 10% -background gray25 -set MBR "%[minimum-bounding-box]" -fill none -stroke red -strokewidth 1 -draw "polygon %[MBR]" barn-mbr.png
旋轉校正圖片
使用 %[minimum-bounding-box:unrotate] 來校正圖像可能存在的任何旋轉。除非您指定圖像方向,否則旋轉校正角度應正確地將圖像與 <= 45 度的角度的正確坐標軸對齊。對於 > 45 度的角度,圖像將與錯誤的坐標軸對齊。設定正確的圖像方向以確保返回正確的旋轉校正角度。使用 -define minimum-bounding-box:orientation={landscape,portrait} 來設定圖像方向。請注意,與凸包一樣,字串格式對可選的 -fuzz 值和可選的 -background 顏色敏感。
上面的穀倉圖像旋轉了 20 度。以下是如何自動校正旋轉並將其返回到其原始橫向方向的方法
magick barn_rotate20.jpg -fuzz 15% -set option:angle "%[minimum-bounding-box:unrotate]" -background gray -rotate "%[angle]" -trim barn_unrotate.jpg