Mat to Byte[] conversion not working in java
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:
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!");
"... which is not working" - so ?
we probably need to see your code.
updated with code
the
webcam_image.get(0,0,frameArray);
.looks correct. again, you're unclear about the problem.Yes,
but
MatOfByte inputframe=new MatOfByte(frameArray);
also
inputframe.fromArray(frameArray);
inputframe.put(0,0,frameArray);
your MatOfBytes results in a long, vertical, 1pixel strip. try:
Thanks Berek , You saved the day.