首页 > 解决方案 > 将屏幕截图加载到 Mat 中

问题描述

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

我该如何规避这个问题?

标签: javaopencvbufferedimagemat

解决方案


我在这个线程上找到了一个解决方法,紫外线的响应解决了这个问题。

工作代码:

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);

}

推荐阅读