Mat to Byte[] conversion not working in java

asked 2015-02-10 01:14:41 -0500

jishnu gravatar image

updated 2015-02-10 04:03:01 -0500

I tried to convert Mat to byte array in java . On conversion of Mat to Byte[] and Byte[] to Mat, I am not able to retain the original value of Mat. The .get method in Mat has parameter which is not working. Can anyone help me with the same?

Use Case: To grab each frame of video and send it via kafka to consumer containing byte[] message then consumer would recieve the byte array and convert to Mat and save it as image.

I came accross similar posts in java but no solution was found. link

See my code:

    MatOfByte webcam_image = new MatOfByte();
    VideoCapture capture = new VideoCapture(
    System.out.println("Frame Grabber started");
    byte[] frameArray;
    int i=0;
    if (capture.isOpened()) {
        while (true) {
            frameArray = new byte[(int) ( * webcam_image
            if (!webcam_image.empty()) {                    
            //  System.out.print(".");  

                producer.send(new KeyedMessage<String, byte[]>("imageTopic",frameArray));

                //Below statements are only for debugging
                MatOfByte inputframe=new MatOfByte(frameArray);
                boolean b=  Highgui.imwrite("/home/jishnu/CodeT/Today7.jpeg", inputframe);

                if(b){System.out.println("save image success");}
                else System.out.println("save image failed");

                b=  Highgui.imwrite("/home/jishnu/CodeT/Today6.bmp",inputframe);

                if(b){System.out.println("save image success");System.exit(0);}
                else System.out.println("save image failed");

            } else {
                System.out.println(" --(!) No captured frame -- Break!");
edit retag flag offensive close merge delete


"... which is not working" - so ?

we probably need to see your code.

berak gravatar imageberak ( 2015-02-10 03:03:15 -0500 )edit

updated with code

jishnu gravatar imagejishnu ( 2015-02-10 04:03:46 -0500 )edit

the webcam_image.get(0,0,frameArray); .looks correct. again, you're unclear about the problem.

berak gravatar imageberak ( 2015-02-10 04:17:55 -0500 )edit


Highgui.imwrite("path/filename.bmp",iwebcame_image); // Creates image in folder


MatOfByte inputframe=new MatOfByte(frameArray);

Highgui.imwrite("path/fname.jpeg", inputframe);// creates Black  image



Highgui.imwrite("path/filename1.jpeg", inputframe);// creates image Black


            b=  Highgui.imwrite("path/file.bmp",inputframe);//Creates Black image
jishnu gravatar imagejishnu ( 2015-02-10 06:21:03 -0500 )edit

your MatOfBytes results in a long, vertical, 1pixel strip. try:


Mat out = new Mat( webcam_image.size(), webcam_image.type());
out.put(0,0, frameArray);
berak gravatar imageberak ( 2015-02-10 06:35:57 -0500 )edit

Thanks Berek , You saved the day.

jishnu gravatar imagejishnu ( 2015-02-13 00:57:48 -0500 )edit