BufferImage和Mat互轉
阿新 • • 發佈:2019-02-10
/** * BufferedImage轉換成Mat * * @param original * 要轉換的BufferedImage * @param imgType * bufferedImage的型別 如 BufferedImage.TYPE_3BYTE_BGR * @param matType * 轉換成mat的type 如 CvType.CV_8UC3 */ public static Mat BufImg2Mat (BufferedImage original, int imgType, int matType) { if(original == null) { throw new IllegalArgumentException("original == null"); } // Don't convert if it already has correct type if (original.getType() != imgType) { // Create a buffered image BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), imgType);// Draw the image onto the new buffer Graphics2D g = image.createGraphics(); try { g.setComposite(AlphaComposite.Src); g.drawImage(original, 0, 0, null); } finally { g.dispose(); } } byte[] pixels = ((DataBufferByte) original.getRaster().getDataBuffer()).getData();Mat mat = Mat.eye(original.getHeight(), original.getWidth(), matType); mat.put(0, 0, pixels); return mat;
}
//Mat轉換為BufferedImage public static BufferedImage matToBufferedImage(Mat mat) { if (mat.height() > 0 && mat.width() > 0) { BufferedImage image = new BufferedImage(mat.width(), mat.height(), BufferedImage.TYPE_3BYTE_BGR); WritableRaster raster = image.getRaster(); DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); byte[] data = dataBuffer.getData(); mat.get(0, 0, data); return image; } return null; }