マイペースなプログラミング日記

DTMやプログラミングにお熱なd-kamiがマイペースに書くブログ

コントラストの拡大

画像のコントラストの拡大をやってみた。モノクロ画像が対象。カモのピンボケ写真で試したところ背景やカモの一部が濃くなったけど顔が見づらくなった

require 'pureimage'

png = PureImage::PNGIO.new
src_image = png.load("mono_kamo.png")
width = src_image.width
height = src_image.height

dst_image = PureImage::Image.new(width, height, 0xffffffff)

sum = 0

for y in 0..height - 1
    for x in 0..width - 1
        pixel = src_image.get(x, y)
        sum += pixel[0]
    end
end

avg = sum.to_f / (width * height)

for y in 0..height - 1
    for x in 0..width - 1
        pixel = src_image.get(x, y)
        new_mono = (2.0 * (pixel[0].to_f - avg) + avg).to_i
        if(new_mono > 255)
            new_mono = 255
        elsif(new_mono < 0)
            new_mono = 0
        end

        dst_image.set(x, y, [new_mono, new_mono, new_mono, 255])
    end
end

png.save(dst_image, 'contrast_kamo.png')

実行結果