简体   繁体   中英

Convert image in Mat to BufferedImage

I have this source code which can open image for OpenCv in Mat then do some operation then bufferedImage should convert it to image so it can be displayed in JFrame. But I can not figure out how to pass arguments.

public class objectDetection{


    public void getMatImg(){

        Mat imageInMat = Imgcodecs.imread(getClass().getResource("lena.png").getPath());
    }

    /*
    *
    *    OpenCV code
    */


    public static BufferedImage bufferedImage(Mat m) {


        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (m.channels() > 1) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);

        m.get(0, 0, ((DataBufferByte)image.getRaster().getDataBuffer()).getData());
        return image;

    }

Here's some code we used a while ago for 2.4.8 or .9. Let me know if it works for you.

I think we may have had some problems with it when we tried to pass in an existing BufferedImage, but it worked fine if you pass in null for the BufferedImage.

/**  
 * Converts/writes a Mat into a BufferedImage.  
 *  
 * @param matrix Mat of type CV_8UC3 or CV_8UC1  
 * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY  
 */  
public static BufferedImage matToBufferedImage(Mat matrix, BufferedImage bimg)
{
    if ( matrix != null ) { 
        int cols = matrix.cols();  
        int rows = matrix.rows();  
        int elemSize = (int)matrix.elemSize();  
        byte[] data = new byte[cols * rows * elemSize];  
        int type;  
        matrix.get(0, 0, data);  
        switch (matrix.channels()) {  
        case 1:  
            type = BufferedImage.TYPE_BYTE_GRAY;  
            break;  
        case 3:  
            type = BufferedImage.TYPE_3BYTE_BGR;  
            // bgr to rgb  
            byte b;  
            for(int i=0; i<data.length; i=i+3) {  
                b = data[i];  
                data[i] = data[i+2];  
                data[i+2] = b;  
            }  
            break;  
        default:  
            return null;  
        }  

        // Reuse existing BufferedImage if possible
        if (bimg == null || bimg.getWidth() != cols || bimg.getHeight() != rows || bimg.getType() != type) {
            bimg = new BufferedImage(cols, rows, type);
        }        
        bimg.getRaster().setDataElements(0, 0, cols, rows, data);
    } else { // mat was null
        bimg = null;
    }
    return bimg;  
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM