将屏幕截图加载到Mat中

时间:2018-11-10 13:04:45

标签: java opencv bufferedimage mat

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

0

我收到此错误:

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;

}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

}