我正在使用机器人捕获屏幕截图。为了避免不必要的I / O,将BufferedImage写入磁盘,然后将其重新加载到Mat中,我尝试使用以下代码将BufferedImage直接加载到Mat中。

public static Mat screenShot() throws AWTException, IOException {

    Robot r = new Robot();
    Rectangle capture =  new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage Image = r.createScreenCapture(capture);
    Mat mat = new Mat(Image.getHeight(), Image.getWidth(), CvType.CV_8UC1);
    byte[] data = ((DataBufferByte) Image.getRaster().getDataBuffer()).getData();
    mat.put(0, 0, data);
    return mat;

}

我收到此错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte

我应该如何规避这个问题?

最佳答案

我在this线程上找到了解决方法,紫外线的响应处理了该问题。

工作代码:

public static Mat screenShot() throws AWTException, IOException {

    Robot r = new Robot();
    Rectangle capture =  new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage Image = r.createScreenCapture(capture);
    Mat mat = BufferedImage2Mat(Image);

    return mat;

}

public static Mat BufferedImage2Mat(BufferedImage image) throws IOException {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", byteArrayOutputStream);
    byteArrayOutputStream.flush();
    return Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);

}

09-11 17:19