- 前言:很多时候为了验证不同平台下编解码方式不同对深度模型推理的干扰,这时需要使用加载2进制数据的方式在不同平台上对齐数据,这是用到了图像转二进制和加载二进制数据为图像数据。下面直接上代码:
- 图像保存二进制数据
[先在循环外定义static int save_count]
save_count++;
std::string ssave_cnt = std::to_string(save_count);
std::string file_name = ssave_cnt+".bin";
FILE *fpw = fopen(file_name.c_str(), "wb");
if ( fpw == NULL )
{
std::cout << "Open error!" << std::endl;
fclose(fpw);
return;
}
if ( !img_rgba.data || img_rgba.channels() != 4 )
{
std::cout << "Image read failed or image channels isn‘t equal to 3."
<< std::endl;
return;
}
int labelw = 1;
int rows = img_rgba.rows;
int cols = img_rgba.cols;
fwrite( &labelw, sizeof(char), 1, fpw );
char* dp = (char*)img_rgba.data;
for ( int i=0; i<rows*cols; i++ )
{
fwrite( &dp[i*4], sizeof(char), 1, fpw );
fwrite( &dp[i*4+1], sizeof(char), 1, fpw );
fwrite( &dp[i*4+2], sizeof(char), 1, fpw );
fwrite( &dp[i*4+3], sizeof(char), 1, fpw );
}
fclose(fpw);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
save_count++;
std::string ssave_cnt = std::to_string(save_count);
std::string file_name = "/Users/gd-npc-701/Desktop/bin_files/"+ssave_cnt+".bin";
int rows = 1920;
int cols = 1080;
FILE *fpr = fopen( file_name.c_str(), "rb" );
if ( fpr == NULL )
{
std::cout << "Open error!" << std::endl;
fclose(fpr);
return;
}
int labelr(0);
fread( &labelr, sizeof(char), 1, fpr );
std::cout << "label: " << labelr << std::endl;
cv::Mat img_rgba_from_bin( rows, cols, CV_8UC4, cv::Scalar::all(0) );
unsigned char* pData = (unsigned char*)img_rgba_from_bin.data;
for ( int i=0; i<rows*cols; i++ )
{
fread( &pData[i*4], sizeof(char), 1, fpr );
fread( &pData[i*4+1], sizeof(char), 1, fpr );
fread( &pData[i*4+2], sizeof(char), 1, fpr );
fread( &pData[i*4+3], sizeof(char), 1, fpr );
}
fclose(fpr);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32