C++ cin 多读取一个字节数据的问题
2017-03-27 10:45
781 查看
1. 前言
最近研究caffe,有一个cifar10的数据集http://www.cs.toronto.edu/~kriz/cifar.html, 但是下载之后只有一个bin文件,无法直观的查看其中的图片,于是我们就想写一个转换函数,将其中的图片数据提取出来。但是遇到了问题。2. 问题描述
官网对bin格式的数据描述如下:Binary version
The binary version contains the files data_batch_1.bin, data_batch_2.bin, …, data_batch_5.bin, as well as test_batch.bin. Each of these files is formatted as follows:
<1 x label><3072 x pixel>
…
<1 x label><3072 x pixel>
In other words, the first byte is the label of the first image, which is a number in the range 0-9. The next 3072 bytes are the values of the pixels of the image. The first 1024 bytes are the red channel values, the next 1024 the green, and the final 1024 the blue. The values are stored in row-major order, so the first 32 bytes are the red channel values of the first row of the image.
Each file contains 10000 such 3073-byte “rows” of images, although there is nothing delimiting the rows. Therefore each file should be exactly 30730000 bytes long.
我们的初始代码如下:
图像数据好像没啥多大问题,不过数据的标签弄错了
void ReadCifar10::LoadAndSaveBinFile(string name, string folder){ char label; ifstream fin(name, ios::binary); for (int j = 0; j < 10000; j++){ fin >> label; char buffer[3][1024] = { 0 }; vector<Mat> channels; for (int i = 2; i >= 0; i--){ fin.read(buffer[i], 1024); channels.emplace_back(Mat(32, 32, CV_8UC1, buffer[i])); } Mat src; merge(channels, src); imwrite(folder + "\\" + to_string(j) + ".jpg", src);
3. 分析问题
我们一开始怀疑是不是我们下载的数据集出现了什么问题,然而通过查看数据内容发现没有问题。接着我们试着在代码种加入一定的调试信息,我们发现读取第二幅图片数据的时候,跳过了标签项数据 09, 也就是说我们多读取了一个字节的数据由此,我们知道了问题所在, 也就是 fin 读取数据的时候会多读取一个字节的数据,导致读取出现问题,采用read方式就可以进行避免了
代码如下:
void ReadCifar10::LoadAndSaveBinFile(string name, string folder){ char label; ifstream fin(name, ios::binary); for (int j = 0; j < 10000; j++){ fin.read(&label, 1); char buffer[3][1024] = { 0 }; vector<Mat> channels; for (int i = 2; i >= 0; i--){ fin.read(buffer[i], 1024); channels.emplace_back(Mat(32, 32, CV_8UC1, buffer[i])); } Mat src; merge(channels, src); imwrite(folder + "\\" + to_string(j) + ".jpg", src); } }
图片提取效果:
4. 小结
这个问题,其实在以前的编程过程种也遇到过,但是没怎么注意,今天特地记录一下,以免以后仍然遇到类似的问题,还是不清楚如何处理。相关文章推荐
- C++ 一个问题:每次读取一个字符存入一个string中,最少读取100个字符,应该如何提高程序的性能?(C++ Primer 9.37 习题)
- 如何用C++读取文本文件中的数据存入到一个数组,并且对该数组任意长度求和
- C#读取C++编写的DLL时遇到的一个问题
- c++中为什么用Send()或send()发送数据时要多发送至少一个字节
- 奇怪的问题--load file导入数据后发现多了一个字符,三个字节
- Ubuntu Eclipse C++ UTF-8转换 (UTF-8:3字节表示一个汉字的问题)
- C++一个类所占字节问题讨论
- C++ 怎么依次读取多个TXT里面的数据,放到一个数组里面
- 获得(读取)一个文件内的所有数据的字节总数
- 将单个字节数据读取到一个float类型的数据中---的几种方法
- C++读取mysql中utf8mb4编码表数据乱码问题及UTF8转GBK编码
- C/C++中读取输入数据时的'\n'问题
- C++读取以空格作为数据区分标记,以回车为行标记的txt文件到一个整数数组(字符串妙用)
- [Flex] flex读取xml格式数据的一个问题
- XML数据读取的问题困扰着我
- [存档]工作中遇到的一个SqlServer2000中大数据量表的检索问题
- 在C++的虚继承中要注意的一个传值问题
- 建了一个"symbina 技术"邮件列表,欢迎大加入到这个群,讨论symbian C++相关的技术问题!
- C++中结构体的字节对齐问题
- 数据绑定应当注意的一个白痴问题