在图像处理工作中,有时候需要保存badcase的现场,方便后续分析或提供给其他人一起分析,那么对于cv::Mat而言,最好的办法是把二进制数据存储为bin文件,后续再读取这个bin文件,就可以恢复现场了。具体的代码如下,以32F为例:
void write_float32_bin(const char* filePath, const cv::Mat& mat) {
FILE* pFile = fopen(filePath, "wb");
if (pFile) {
int mat_bytes = mat.cols * mat.rows * mat.channels();
float* mat_data = (float*)(mat.data);
for (int i = 0; i < mat_bytes; i++) {
fwrite((mat_data + i), 4, 1, pFile);
}
fclose(pFile);
} else {
printf("can not write file %s\n", filePath);
}
}
void read_float32_bin(const char* filePath, cv::Mat& mat) {
FILE* pFile = fopen(filePath, "rb");
if (pFile) {
int mat_bytes = mat.cols * mat.rows * mat.channels();
float* mat_data = (float*)(mat.data);
for (int i = 0; i < mat_bytes; i++) {
float value = 0.f;
fread(&value, 4, 1, pFile);
*(mat_data + i) = (float)value;
}
fclose(pFile);
} else {
printf("cannot open file %s\n", filePath);
}
}