OpenCV 读取 Cifar 数据集

来源:互联网 发布:windows下svn钩子 编辑:程序博客网 时间:2024/05/22 22:31

欢迎访问人工智能研究网 www.studyai.cn

OpenCV 读取 Cifar 数据集(来自studyai.cn)

Cifar数据集的下载地址[http://www.cs.toronto.edu/~kriz/cifar.html]

下载C语言版本的数据集
CIFAR-10 binary version (suitable for C programs) 162 MB c32a1d4ab5d03f1284b67883e8d87530

程序代码

#include <string>#include <iostream>#include <fstream>#include <vector>#include <opencv2\opencv.hpp>using namespace std;using namespace cv;bool ReadCifar10DataBatch(const string& dir, const string& batchName, size_t imgCount, vector<Mat>& images, vector<int>& labels){    const int PATCH_SIZE = 32;          //图像块的尺寸: 32*32    const int N_CHANEL = 3;             //通道数    const int LINE_LENGTH = PATCH_SIZE * PATCH_SIZE * N_CHANEL + 1;//以字节为单位    bool isSuccess = false;    fstream fs(dir + batchName, ios::in | ios::binary);//以二进制方式读取    if (fs.is_open())    {        cout << "成功打开文件: " << batchName << endl;        char buffer[LINE_LENGTH];        for (size_t imgIdx = 0; imgIdx < imgCount; imgIdx++)        {            fs.read(buffer, LINE_LENGTH);            int class_label = (int)buffer[0];//类别标签:buffer[0]            Mat red_img(32, 32, CV_8UC1, &buffer[1]);//红色通道:buffer[1->1024]            Mat green_img(32, 32, CV_8UC1, &buffer[1025]);//绿色通道:buffer[1025->2048]            Mat blue_img(32, 32, CV_8UC1, &buffer[2049]);//蓝色通道:buffer[2049->3072]            vector<Mat> bgrMats = { blue_img, green_img, red_img };//OpenCV的通道顺序是BGR            Mat rgb_img;            cv::merge(bgrMats, rgb_img);//RGB通道融合            //将样本和对应的标签加入集合            images.push_back(rgb_img);            labels.push_back(class_label);        }        isSuccess = true;    }    else    {        cout << "无法打开文件: " << batchName << endl;        isSuccess = false;    }    fs.close();    return isSuccess;}int main(int argc, char* argv[]){    const string dir = "F:\\cifar-10-binary\\cifar-10-batches-bin\\";    const string class_names[10] =    {        "airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"    };    const string batch_names[6] =    {        "data_batch_1.bin", "data_batch_2.bin", "data_batch_3.bin",        "data_batch_4.bin", "data_batch_5.bin", "test_batch.bin"    };    size_t ImgCountPerBatch = 10000;    vector<Mat> images;    vector<int> labels;    bool success = ReadCifar10DataBatch(dir, batch_names[2], ImgCountPerBatch, images, labels);    if (success)    {        for (size_t imgIdx = 0; imgIdx < images.size(); imgIdx++)        {            Mat BigImg; cv::resize(images[imgIdx], BigImg, Size(128, 128));            imshow("cifar image", BigImg);            cout << "image index: "<<imgIdx<<"---->class label,name :"                 << labels[imgIdx] << "<->" << class_names[labels[imgIdx]] << endl;            cv::waitKey(5);        }    }    system("pause");    return 0;}
1 0