使用java

时间:2017-04-01 16:18:15

标签: java

我正在尝试使用颜色分割来分割图像我已经在互联网上找到了一些代码但是它适用于黄色和绿色我一直在尝试将其用于其他颜色,但它在这里工作是不是代码。我正在使用BoofCV库

public class ExampleSegmentColor 
{
public static void printClickedColor( final BufferedImage image ) {
    ImagePanel gui = new ImagePanel(image);
    gui.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            float[] color = new float[3];
            int rgb = image.getRGB(e.getX(),e.getY());
            ColorHsv.rgbToHsv((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF, color);
            System.out.println("H = " + color[0]+" S = "+color[1]+" V = "+color[2]);

            showSelectedColor("Selected",image,color[0],color[1]);
        }
    });

    ShowImages.showWindow(gui,"Color Selector");
}

public static void showSelectedColor( String name , BufferedImage image , float hue , float saturation ) {
    Planar<GrayF32> input = ConvertBufferedImage.convertFromMulti(image,null,true,GrayF32.class);
    Planar<GrayF32> hsv = input.createSameShape();

    // Convert into HSV
    ColorHsv.rgbToHsv_F32(input,hsv);

    // Euclidean distance squared threshold for deciding which pixels are members of the selected set
    float maxDist2 = 0.4f*0.4f;

    // Extract hue and saturation bands which are independent of intensity
    GrayF32 H = hsv.getBand(0);
    GrayF32 S = hsv.getBand(1);

    // Adjust the relative importance of Hue and Saturation.
    // Hue has a range of 0 to 2*PI and Saturation from 0 to 1.
    float adjustUnits = (float)(Math.PI/2.0);

    BufferedImage output = new BufferedImage(input.width,input.height,BufferedImage.TYPE_INT_RGB);
    for( int y = 0; y < hsv.height; y++ ) {
        for( int x = 0; x < hsv.width; x++ ) {

            float dh = UtilAngle.dist(H.unsafe_get(x,y),hue);
            float ds = (S.unsafe_get(x,y)-saturation)*adjustUnits;

            float dist2 = dh*dh + ds*ds;
            if( dist2 <= maxDist2 ) {
                output.setRGB(x,y,image.getRGB(x,y));
            }
        }
    }

    ShowImages.showWindow(output,"Showing "+name);
}

public static void main( String args[] ) {
    BufferedImage image = UtilImageIO.loadImage(UtilIO.pathExample("sunflowers.jpg"));

    // Let the user select a color
    printClickedColor(image);
    // Display pre-selected colors
    showSelectedColor("Yellow",image,1f,1f);
    showSelectedColor("Green",image,1.5f,0.65f);
}

}

0 个答案:

没有答案