问题描述:

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 Mat .get accepts byte[] as 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. here

See my code:

` System.loadLibrary("opencv_java249");

MatOfByte webcam_image = new MatOfByte();

VideoCapture capture = new VideoCapture(

"/home/jishnu/CodeT/TrainingDataSet/Video.mp4");

System.out.println("Frame Grabber started");

byte[] frameArray;

int i=0;

if (capture.isOpened()) {

while (true) {

capture.read(webcam_image);

frameArray = new byte[(int) (webcam_image.total() * webcam_image

.channels())];

if (!webcam_image.empty()) {

// System.out.print(".");

webcam_image.get(0,0,frameArray);

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

//Below statements are only for debugging

System.out.println(frameArray.length);

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");

inputframe.fromArray(frameArray);

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!");

`

网友答案:

It's working me.I use apachi-common for write and read from file.

public static void save(Mat mat, String name)
        {
            File file = new File(path, name);
            int length = (int) (mat.total() * mat.elemSize());
            byte buffer[] = new byte[length];
            mat.get(0, 0, buffer);
            try
                {
                    FileUtils.writeByteArrayToFile(file, buffer);
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
        }

 public static Mat load(String name)
        {
            File file = new File(path, name);
            byte[] buffer = new byte[0];
            try
                {
                    buffer = FileUtils.readFileToByteArray(file);
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            Mat mat = new Mat(row, col, type);
            mat.put(0, 0, buffer);
            return mat;
        }
网友答案:

If anyone gets the same error. I used Mat.put(frameArray) to create Mat from byte instead of MatOfByte inputframe=new MatOfByte(frameArray); Now everything is working fine, I dont know why is MatofByte constructor not working.

Fixed in later versions of JavaCV.

相关阅读:
Top