凸包と最小外接矩形
凸包 • 最小外接矩形 • 画像の回転補正
凸包(convex hull)は、その内部にある点の集合を含む最小面積の凸多角形です。凸包は、点の集合の周りに張ったゴムバンドで囲まれる形状として視覚化できます。
convex-hull 文字列フォーマットは、非黒ピクセルをすべて含む凸包多角形の頂点の x,y 座標のリストを返します。
magick [-fuzz value%] [-background background-color] -format "%[convex-hull]" info:
上・右・下・左の極点のみを返すには %[convex-hull:extreme-points] を使います。
ここで文字列フォーマットは、任意の -fuzz 値と、define で指定する任意の背景色に反応します。背景色が定義されていない限り、上記コマンドは fuzz 値に応じて背景色を自動的に見つけます。fuzz 値は指定しない場合 0 が既定です。
たとえば、黒背景上の次の白い矩形を考えます:
![[Convex Hull]](../static/img/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]](../static/img/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]](../static/img/convex-hull-blocks-closure.png)
最後に、-fuzz を使って背景色を判定する、一定でない非黒背景の例を示します:
![[Convex Hull Barn]](../static/img/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]](../static/img/convex-hull-barn-closure.jpg)
最小外接矩形
画像の前景オブジェクトの凸包に似たものに、最小外接矩形(minimum bounding box)があります。外接矩形を構成する点を返すには %[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} を使います。なお、convex-hull と同様、文字列フォーマットは任意の -fuzz 値と任意の -background 色に反応します。
上記の納屋の画像は 20 度回転しています。回転を自動的に補正し、元の横向き(landscape)に戻す方法は次のとおりです:
magick barn_rotate20.jpg -fuzz 15% -set option:angle "%[minimum-bounding-box:unrotate]" -background gray -rotate "%[angle]" -trim barn_unrotate.jpg