RMagickで二値化処理をしてみた。
前回やったエッジ検出が思いのほか楽しかったので二値化処理もやってみた。
処理は超単純。
ピクセルごとにRGB値を合計、しきい値を超えたら白、超えなかったら黒で置き換える。
equire 'rubygems' require "RMagick" include Magick def binarize(file, t) white = Magick::Pixel.new(255, 255, 255) black = Magick::Pixel.new(0, 0, 0) threshold = t; img = ImageList.new(file) for y in 0...img.rows-1 for x in 0...img.columns-1 src = img.pixel_color(x, y) brightness = src.red + src.green + src.blue if brightness > threshold img.pixel_color(x, y, white) else img.pixel_color(x, y, black) end end end img.write "test.jpg" end image = ARGV[0] t = ARGV[1] binarize(image, t.to_i)
本日の実験画像はこちら。昼はお堅い公務員、夜は変態コスプレ殺し屋。
ドグサレヒーローことデストロイマンさんです。
ruby ./binarize.rb image/destroyman.jpg 535