我试图在java中将Mat转换为字节数组。在将Mat转换为Byte[],Byte[]转换为Mat时,我无法保留Mat的原始值。Mat .get接受byte[]作为不起作用的参数。有人能帮我吗?
用例:获取每一帧视频并通过kafka发送给包含byte[]消息的使用者,然后消费者将接收字节数组并转换为Mat并将其保存为图像。
我在java中遇到了类似的帖子,但没有找到解决方案。
请看我的代码:
` 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!");`
发布于 2015-11-11 11:38:00
我用阿帕奇-普通写和读文件。
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;
}发布于 2021-03-06 07:45:13
OpenCV版本: 4.5.1
折射率:https://www.tutorialspoint.com/how-to-convert-opencv-mat-object-to-bufferedimage-object-using-java
public static void main(String[] args) throws IOException {
String filePath = ".jpg";
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Mat mat=Imgcodecs.imread(filePath);
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", mat, matOfByte);
byte[] byteArray = matOfByte.toArray();
Path path = Paths.get("D:\\yyy2.jpg");
Files.write(path, byteArray);
//InputStream inputStream = new ByteArrayInputStream(byteArray);
}发布于 2015-02-13 08:21:44
如果有人犯了同样的错误。我用Mat.put(frameArray)来从字节创建Mat,而不是MatOfByte inputframe=new MatOfByte(frameArray);,现在一切都很好,我不知道为什么MatofByte构造函数不能工作。
修复了JavaCV.的后期版本
https://stackoverflow.com/questions/28426927
复制相似问题