RMagickで簡単なエッジ検出をしてみた。
macportsインストール
そういえば買い替えてからmacportsを入れてなかったので
http://svn.macosforge.org/repository/macports/downloads/からdmgを持って来てインストール。
ImageMagickインストール
http://rmagick.rubyforge.org/install-osx.html を参考にインストール。
# sudo port install tiff -macosx imagemagick +q8 +gs +wmf . . . Error: The following dependencies failed to build: jpeg zlib
zlibとjpegが無いとか言われたのでとりあえずzlibをインストール
# sudo port install zlib
入ったっぽいので試しにもう一度ImageMagickをインストールしてみる。
# sudo port install tiff -macosx imagemagick +q8 +gs +wmf
入った。あれ?jpegは入れてないのに…。
zlibが入ってれば勝手に入れてくれるのかもしれない。分からない。
エッジ検出処理
単純な微分方式で検出することにした。
輪郭ではRGB値が急激に変化すると考えられるので
RGB値それぞれで微分し、傾きがしきい値を超えたら輪郭だと判断する。
require 'rubygems' require "RMagick" include Magick def edgedetect(file) white = Magick::Pixel.new(255, 255, 255) black = Magick::Pixel.new(0, 0, 0) threshold = 12000; img = ImageList.new(file) red_array = Array.new for y in 0...img.rows-1 for x in 0...img.columns-1 src = img.pixel_color(x, y) next_x = img.pixel_color(x+1, y) next_y = img.pixel_color(x, y+1) dr_x = src.red - next_x.red # 対象座標の一つ右のピクセルとのRGB差分を計算(x軸傾き) dg_x = src.green - next_x.green db_x = src.blue - next_x.blue dr_y = src.red - next_y.red # 対象座標の一つ下のピクセルとのRGB差分を計算(y軸傾き) dg_y = src.green - next_y.green db_y = src.blue - next_y.blue dr = dr_x*dr_x + dr_y*dr_y # 対象座標のRGBごとの傾きを算出 dg = dg_x*dg_x + dg_y*dg_y db = db_x*db_x + db_y*db_y if dr + dg + db > threshold # 傾きの合計がしきい値を超えていれば黒、以下なら白を出力(黒が輪郭) img.pixel_color(x, y, black) else img.pixel_color(x, y, white) end end end img.write "holly_edge.jpg" end image = ARGV edgedetect(image)
本日の実験画像はこちら。
モデルでありながら全米殺し屋ランキング6位というマルチな才能と美貌を併せ持つホリーさんです。
画像を指定して実行。
# ruby ./edgedetect.rb image/holly.jpg