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

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

SobelFilter

大学の授業で習ったエッジの検出を行うSobelFilterの水平方向のフィルタを試してみた。あらかじめモノクロ画像を作成しているものとする。ついでに、画像の色を反転させておいた。

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

public class SobelFilter{
    private static final int MASK[][] = {
        {-1, 0, 1},
        {-2, 0, 2},
        {-1, 0, 1}
    };

    public static void main(String[] args) throws Exception{
        BufferedImage image = ImageIO.read(new File("mono_nekobean.png"));

        int width = image.getWidth();
        int height = image.getHeight();

        BufferedImage filterImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB );

        for(int x = 0; x < width; x++){
            for(int y = 0; y < height; y++){
                filter(filterImage, image, x, y);
            }
        }

        ImageIO.write(filterImage, "png", new File("sobel_nekobean.png"));
    }

    private static void filter(BufferedImage filterImage, BufferedImage image, int x, int y){
        int pixel = 0;

        for(int dy = -1; dy <= 1; dy++){
            for(int dx = -1; dx <= 1; dx++){
                pixel += getMonoData(image, x + dx, y + dy) * MASK[dy + 1][dx + 1];
            }
        }

        if(pixel < 0)
            pixel = 0;
        else if(pixel > 255)
            pixel = 255;

        pixel = 255 - pixel;

        pixel = (0xFF << 24) + (pixel << 16) + (pixel << 8) + pixel;

        filterImage.setRGB(x, y, pixel);
    }

    private static int getMonoData(BufferedImage image, int x, int y){
        if(x <= 0)
            x = 0;
        if(y <= 0)
            y = 0;

        if(x >= image.getWidth())
            x = image.getWidth() - 1;
        if(y >= image.getHeight())
            y = image.getHeight() - 1;

        return image.getRGB(x, y) & 0xFF;
    }
}

実行結果


ねこび〜ん by カネウチカズコ is licensed under a Creative Commons 表示-継承 2.1 日本 License.