Search code examples
javabufferedimageedge-detection

Running CannyEdgeDetector.java Example Java


Im trying to run CannyEdgeDetector.java example: This Example

public static void main(String args[]) {

    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("paper3.png"));
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    CannyEdgeDetector detector = new CannyEdgeDetector();
    detector.setSourceImage(img);
    detector.process();
    BufferedImage edges = detector.getEdgesImage();

    File saveFile = new File("out.png");
    try {
        ImageIO.write(edges, "png", saveFile);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

im getting Exception in thread "main" java.lang.IllegalArgumentException: Unsupported image type: 6


Solution

  • The image type of the file that you read is 6, which corresponds to BufferedImage.TYPE_4BYTE_ABGR. This image type is not recognized by the CannyEdgeDetector (see the readLuminance() method of this class for allowed image types). You can convert the image read into the appropriate image type by drawing to a new Image of the appropriate type:

    BufferedImage bufImg = ImageIO.read( imageFile );
    BufferedImage convertedImg = new BufferedImage(bufImg.getWidth(), bufImg.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = convertedImg.createGraphics();
    g2d.drawImage(bufImg, 0, 0, null);
    g2d.dispose();
    ....
    ///now feed convertedImg  into the CannyEdgeDetectory
    detector.setSourceImage(convertedImg);