看到OpenCV的Image类实例一副图像,觉得挺好玩,因此想自己定义一个自己的图像类,让后完成写盘,并且读取出来。没有办法,再利用一下OpenCV的imshow显示一下,看看和自己的预期是否一样。
首先要先定义一个图像类,就叫Image吧!
class Image{
public:// 构造函数,使用行和列来构造(16位图)Image(unsigned short row,unsigned short col):rows(row),cols(col){ID=1001;pixel=new unsigned short[rows*cols];}// 设置图像的像素void setPixel(unsigned short* data){for(int i=0;i<rows*cols;++i){pixel[i]=data[i];}}// 获取图像的像素,返回的是数组指针unsigned short *getPixel()const {return pixel;}// 析构函数~Image(){delete[] pixel;}// 序列化,进行存盘和读取操作void serialize(fstream &fs,bool bWrite);private:// 私有成员,都是16位数据unsigned short ID;unsigned short rows;unsigned short cols;unsigned short *pixel;
};
// 序列化的具体实现
void Image::serialize(fstream &fs, bool bWrite){int pixelLength=rows*cols;if(bWrite){fs.write((char*)&ID,sizeof(ID));fs.write((char*)&rows,sizeof(rows));fs.write((char*)&cols,sizeof(cols));fs.write((char*)*&pixel,sizeof(unsigned short)*pixelLength);}else{fs.read((char*)&ID,sizeof(ID));fs.read((char*)&rows,sizeof(rows));fs.read((char*)&cols,sizeof(cols));fs.read((char*)&pixel[0],sizeof(unsigned short)*pixelLength);}
}
然后我们就在主函数中进行操作吧!
int main()
{// 首先,定义一个文件流fstream file;/*// Prepare the pixel data and write it to a binary file on disk.int r=1024;int c=1024;unsigned short data[r*c]; //data[][200]// 给像素赋值for(int i=0;i<r;i++){for(int j=0;j<c;++j){data[c*i+j]=j%c;}}// 实例化一个imageImage image(r,c);// 设置像素值image.setPixel(data);// 打开文件,状态输出,二进制格式file.open("../data/image.bin",ios::out|ios::binary);image.serialize(file,true); //写文件file.close(); //关闭*/// Read and display the imagefile.open("../data/image.bin",ios::in|ios::binary);file.seekg(0,ios::end);cout<<"File size is: "<<file.tellg()<<endl;file.seekg(0,ios::beg);int row=1024;int col=1024;Image img(row,col);img.serialize(file,false);//cout<<sizeof(img.pixel)/sizeof(img.pixel[0])<<endl;//cout<<img.ID<<endl;//cout<<img.rows<<endl;//cout<<img.cols<<endl;file.close();// 借用OpenCV进行显示cv::Mat im=cv::Mat(row,col,CV_16UC1,img.getPixel());cv::normalize(im,im,0,255,cv::NORM_MINMAX,CV_8UC1);cv::imshow("",im);cv::waitKey();return 0;
}
输出结果:File size is: 2097158
这里我们的像素是1024X1024 16位,因此,它的大小为2097152,然后在Image中的ID,rows和cols都是16位,所以共占用6个字节,因此,整个文件就是2097158个字节。
输出的图像在下面
最后,如果你使用的是Mac Sonama 14.1系统的话,使用QtCreateor的IDE的话,有时候你运行程序就会出现如下提示
不要慌张,把你的输入法切换到英文就行了,再次运行就没有这个抱怨了。