RMagickでconvolve

ImageMagickのドキュメントのDiscrete Laplacian Kernelsに以下のサンプルがある。

convert xc: -define showkernel=1 -precision 2 \
    -morphology Convolve:0 Laplacian:0 null:
convert face.png -define convolve:scale='!' -bias 50% \
    -morphology Convolve Laplacian:0   face_laplacian_0.png

一行目はカーネルを表示するためのもので、これを実行すると次の結果になる。

$ /usr/local/opt/imagemagick@6/bin/convert xc: -define showkernel=1 -precision 2 \
    -morphology Convolve:0 Laplacian:0 null:
Kernel "Laplacian" of size 3x3+1+1 with values from -1 to 8
Forming a output range from -8 to 8 (Zero-Summing)
 0:    -1    -1    -1
 1:    -1     8    -1
 2:    -1    -1    -1

ImageMagick 7.xではコマンドラインが変更になっているのか、ドキュメント中の出力のようにはならなかったのでImageMagick 6.xで実行している。どのみちRMagickがリンクするImageMagickも6.xでなければならないので問題ない。

画像処理をしているのは二行目なのだが、一行目にはなかった-define convolve:scale='!'という指定が加っているため、実際に使用されるカーネルは変わってしまうようだ。二行目の実行にあたっても-define showkernel=1を指定しておくとそれを確認できる。

$ /usr/local/opt/imagemagick@6/bin/convert face.png -define showkernel=1 -define convolve:scale='!' -bias 50% \
    -morphology Convolve Laplacian:0   face_laplacian_0.png
Kernel "Laplacian" of size 3x3+1+1 with values from -0.125 to 1
Forming a output range from -1 to 1 (Zero-Summing)
 0:    -0.125    -0.125    -0.125
 1:    -0.125         1    -0.125
 2:    -0.125    -0.125    -0.125

これと同じことをRMagickを使って行おうとすると、どうやら以下のようになるらしい。

require 'rmagick'

orig_img = Magick::Image.read('face.png').first
orig_img.bias = 0.5

kernel = [
  -0.125, -0.125, -0.125,
  -0.125,  1,     -0.125,
  -0.125, -0.125, -0.125,
]
img = orig_img.convolve(3, kernel)
img.write('face_laplacian_0-rmagick.jpg')