无法从Java读取C++中保存的Opencv Mat映像

Cannot Read Saved Opencv Mat Image in C++ From Java

本文关键字:保存 Opencv Mat 映像 C++ Java 读取      更新时间:2023-10-16

我想在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需要的所有信息,并且应该具有与您的方法几乎相同的文件大小和性能。