ImageMagickとmulticropコマンドで1枚の画像を空白区切りで分割してみる

まえがき

友人から複数枚の画像を1枚の画像としてスキャンしたものをいい感じに分割する方法がなさそうか困っていそうだった。
見てググって出てきた内容は今後使う時がありそうな気がしたのでメモを残しておく。

やりたいこと

こういう1枚のスキャン画像に複数枚の画像がまとめられている。
これを1枚ずつ分割して保存したい。
以下の例でいうと、4分割してimage-1.png, image-2.png, image-3.png, image-4.pngといった具合に分割保存したい。

f:id:st1t:20200604223202p:plain

調べた結果

ImageMagickをラップしたmulticropというスクリプトを使うと良さそう。

www.fmwconcepts.com

インストール方法

ImageMagick

imagemagick.org

multicrop

以下公式サイトの Download Script からダウンロードして実行権限と付与しておく。
Fred's ImageMagick Scripts: MULTICROP

multicrop依存のもの

REQUIREMENTS: If using unrotate method 2, then my script, unrotate, is required. If using innertrim, then my script, autotrim is required.

作者の別のスクリプトも必要みたいなのでダウンロードして実行権限とpathを通しておく。
今回はunrotateだけあれば動いたのでそれだけ紹介。

Fred's ImageMagick Scripts: UNROTATE

実行コマンド

f:id:st1t:20200604223202p:plain

↑の画像をtest-image.pngとして実行。

$ ./multicrop -b white test-image.png image.png

Processing Image 0
Initial Crop Box: 220x188+37+41

convert: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG `image-000.png' @ warning/png.c/MagickPNGWarningHandler/1748.
Processing Image 1
Initial Crop Box: 220x188+309+41

convert: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG `image-001.png' @ warning/png.c/MagickPNGWarningHandler/1748.
Processing Image 2
Initial Crop Box: 220x188+37+279

convert: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG `image-002.png' @ warning/png.c/MagickPNGWarningHandler/1748.
Processing Image 3
Initial Crop Box: 220x188+309+279

convert: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG `image-003.png' @ warning/png.c/MagickPNGWarningHandler/1748.

$ 

実行結果

以下のように4分割されて出力された。
ただ、実際はスキャン画像の解像度や色によって画像と画像の間の部分を認識する精度がそのままだとでなさそうだった。
この辺はmulticropのパラメータを調整してみる必要がありそう。

f:id:st1t:20200604225226p:plain