无法从Java读取C++中保存的Opencv Mat映像
Cannot Read Saved Opencv Mat Image in C++ From Java
我想在C++中的txt文件中将OpenCV Mat图像保存为字节数据。然后,我想用Java读取该文件并获得此图像。我的C++代码:
std::ofstream tileData;
tileData.open("image.txt", std::ios::app |
std::ios::binary);
cv::Mat temp = imread("image.png",1);
std::vector<uchar> array(temp.rows * temp.cols);
array.assign(temp.datastart, temp.dataend);
tileData.write(reinterpret_cast<char*>(array.data()), sizeof(uchar)*array.size());
tileData.close();
我的Java代码:
public static void main(String[] args) throws IOException {
File file = new File("image.txt");
byte[] buf = getBytesFromFile(file);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(buf));
}
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
throw new IOException("File is too large!");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
当我调试Java代码时,它说img为null。你能提供一个用Java读取这个txt文件的解决方案吗?
您不能使用ImageIO读取字节文本文件。你使用的是你自己的图像格式,没有像大小这样的元信息。您可以将元信息添加到字节文件中并使用自己的自定义图像格式,也可以使用编码非常简单且无需压缩的图像格式(如位图(。它包含ImageIO需要的所有信息,并且应该具有与您的方法几乎相同的文件大小和性能。
相关文章:
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 无法从Java读取C++中保存的Opencv Mat映像
- 在opencv c++目录中从/加载/保存多个图像
- 如果我想通过OpenCV dnn模块加载PyTorch的模型,我应该如何保存它
- OpenCV imwrite不会保存图像
- 如何将捕获的图像存储在OpenCV中(将图片保存到计算机)
- 有没有办法拿一个opencv显示窗口并将其保存到GUI窗口?
- 对 OpenCV C++ 程序进行单元测试,该程序拍摄照片并将其保存到文件中
- Opencv 保存视频
- 我想将 OpenCV 中处理后的图像保存为“input_name+enhanced.input_image_format
- OpenCV - 在矢量<Mat>中保存垫子
- 在Ubuntu中使用VideOwriter(OpenCV)保存视频作为MP4时出错
- 无法将图像保存在具有白色背景的JPG中 OpenCV
- 将 OpenCV MAT 保存到 TXT 文件作为不带分隔符的十六进制值
- OpenCV 4.0 无法保存视频
- 视频编写器功能不会使用 OpenCV-3.0.0 保存文件
- 无法使用cv :: imwrite保存垫子图像在JNI本机代码OPENCV中
- OPENCV IMWRITE保存黑色PNG
- 使用 OpenCV 保存 .pgm 图像时出错
- 保存 OpenCV 上 Hough Circle 检测到的圆圈内的内容