C++版的神经网络训练用的图像集合加载
1、构造图像的基本单元类
class ImgUnit { public: ImgUnit(unsigned char *p) { for(int i=0;i<3;i++) { unsigned char *pp=p+1+i*1024; m[i]=Mat(32,32,CV_8U,pp); } merge(m,3,m_bgr); label=(int)p[0]; // imshow("img unit",m_bgr); } ImgUnit(){} void makeImg(unsigned char *p) { for(int i=0;i<3;i++) { unsigned char *pp=p+1+i*1024; m[(2-i)]=Mat(32,32,CV_8U,pp); } merge(m,3,m_bgr); label=(int)p[0]; } Mat m[3]; Mat m_bgr; int label; }; //1.加载训练图片 void loadImgSet(ImgUnit *imgset,string datapath) { unsigned char* p=new unsigned char[30730000]; ifstream infile(datapath,ios::binary); if(!infile) { cerr<<"open err!"<<endl; exit(1); } infile.read((char*)p,30730000); for(int i=0;i<10000;i++) { uchar* pi=p+i*3073; imgset[i].makeImg(pi); } infile.close(); }
2. 测试程序
#include <iostream> #include<opencv2/opencv.hpp> #include<myfunction.hpp> #include<iostream> #include<fstream> #include<string.h> using namespace cv; using namespace std; int main() { ImgUnit* imgset=new ImgUnit[10000]; string datapath="D:/Qt/MyImage/cifar10/data_batch_1.bin"; loadImgSet(imgset,datapath); Mat ms[100]; Mat implay(640,640,CV_8UC3,Scalar::all(0)); for(int i=0;i<100;i++) { resize(imgset[i+100].m_bgr,ms[i],Size(64,64),0,0,INTER_CUBIC); int y=i/10,x=i%10; Mat temp=implay(Rect(x*64,y*64,64,64)); ms[i].copyTo(temp); } imshow("100 image",implay); waitKey(); delete [] imgset; return 0; }
运行结果如下,显示了一百幅图像,说真的,我人眼都识别不了,不知道机器式怎么识别的:) :