Java BufferedImage Filter filterFillHoles(BufferedImage img)

Here you can find the source of filterFillHoles(BufferedImage img)

Description

filter Fill Holes

License

Apache License

Declaration

public static BufferedImage filterFillHoles(BufferedImage img) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.Color;
import java.awt.image.BufferedImage;

public class Main {
    public static BufferedImage filterFillHoles(BufferedImage img) {
        int x, y;

        final int w = img.getWidth();
        final int h = img.getHeight();
        final BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

        for (y = 0; y < h; y++) {
            for (x = 0; x < w; x++) {
                dst.setRGB(x, y, img.getRGB(x, y));
            }/*from  ww w. j a  v a  2s  . com*/
        }
        for (y = 0; y < h; y++) {
            for (x = 2; x < w - 2; x++) {
                int c1, c2, c3, c4, c5;
                c1 = new Color(img.getRGB(x - 2, y)).getRed();
                c2 = new Color(img.getRGB(x - 1, y)).getRed();
                c3 = new Color(img.getRGB(x, y)).getRed();
                c4 = new Color(img.getRGB(x + 1, y)).getRed();
                c5 = new Color(img.getRGB(x + 2, y)).getRed();

                if (c1 < 127 && c2 < 127 && c3 > 128 && c4 < 127) {
                    c3 = (c1 + c2 + c4) / 3;
                } else if (c2 < 127 && c3 > 128 && c4 < 127 && c5 < 127) {
                    c3 = (c2 + c4 + c5) / 3;
                }
                dst.setRGB(x, y, new Color(c3, c3, c3).getRGB());
            }
        }
        for (x = 0; x < w; x++) {
            for (y = 2; y < h - 2; y++) {
                int c1, c2, c3, c4, c5;
                c1 = new Color(img.getRGB(x, y - 2)).getRed();
                c2 = new Color(img.getRGB(x, y - 1)).getRed();
                c3 = new Color(img.getRGB(x, y)).getRed();
                c4 = new Color(img.getRGB(x, y + 1)).getRed();
                c5 = new Color(img.getRGB(x, y + 2)).getRed();

                if (c1 < 127 && c2 < 127 && c3 > 128 && c4 < 127) {
                    c3 = (c1 + c2 + c4) / 3;
                } else if (c2 < 127 && c3 > 128 && c4 < 127 && c5 < 127) {
                    c3 = (c2 + c4 + c5) / 3;
                }
                dst.setRGB(x, y, new Color(c3, c3, c3).getRGB());
            }
        }
        return dst;

    }
}

Related

  1. applyFilter(BufferedImage img, ImageFilter filter)
  2. applyFilter(LookupTable lookupTable, BufferedImage srcImg)
  3. filter(BufferedImage image, BufferedImageOp op)
  4. filterContrast(BufferedImage img)
  5. filterDetectLines(BufferedImage img)
  6. filterImage(BufferedImageOp bufferedImageOp, BufferedImage srcImg, BufferedImage dstImg)
  7. filterMedian(BufferedImage img)
  8. filterScale(BufferedImage img, float ratio)
  9. filterSmooth(BufferedImage img)