我想在C ++中将OpenCV Mat图像保存为txt文件中的字节数据。然后,我想用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为空。您能否提供一种使用Java读取此txt文件的解决方案?
答案 0 :(得分:1)
您不能使用ImageIO读取字节文本文件。您正在使用自己的图像格式,而没有诸如大小之类的元信息。您可以将元信息添加到字节文件中并使用自己的自定义图像格式,也可以使用编码非常简单且没有压缩的图像格式(例如位图)。它包含ImageIO所需的所有信息,并且文件大小和性能应与您的方法几乎相同。