将屏幕截图加载到 Mat

Loading screenshot into Mat

我正在使用机器人截取屏幕截图。为了避免不必要的 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);

}