1. 程式人生 > >OpenCV Java 問題記錄 - Mat型別和BufferedImage型別的相互轉化

OpenCV Java 問題記錄 - Mat型別和BufferedImage型別的相互轉化

將Mat型別轉化成BufferedImage型別

/**
* 將Mat型別轉化成BufferedImage型別
* 
* @param amatrix Mat物件
* @param fileExtension 副檔名
* @return
*/
public static BufferedImage Mat2Img(Mat mat, String fileExtension) {
    MatOfByte mob = new MatOfByte();


    Highgui.imencode(fileExtension, mat, mob);
    // convert the "matrix of bytes" into a byte array
    byte[] byteArray = mob.toArray();
    BufferedImage bufImage = null;
    try {
        InputStream in = new ByteArrayInputStream(byteArray);
        bufImage = ImageIO.read(in);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bufImage;
}

將BufferedImage型別轉換成Mat型別 

/**
* 將BufferedImage型別轉換成Mat型別 
* @param bfImg
* @param imgType bufferedImage的型別 如 BufferedImage.TYPE_3BYTE_BGR
* @param matType 轉換成mat的type 如 CvType.CV_8UC3
* @return
*/
public static Mat Img2Mat(BufferedImage bfImg, int imgType, int matType) {
    BufferedImage original = bfImg;
    int itype = imgType;
    int mtype = matType;
    
    if (original == null) {
        throw new IllegalArgumentException("original == null");
    }
    
    if (original.getType() != itype) {
        BufferedImage image = new BufferedImage(original.getWidth(),                                                        original.getHeight(), itype);

        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(), mtype);
    mat.put(0, 0, pixels);

    return mat;
}