自定义图像类
一、序言:在图像处理的学习过程中,我们会经常使用到C++中比较著名的一些图像处理库中的图像类或矩阵类,如OpenCV中的Mat等。今天,我们就来实现自己的图像类。
二、需求:
1.一个完整的图像处理类通常包括以下属性:
(1)Width 宽
(2)Height 高
(3)nBitCount 一个像素的所需的字节数
(4)BytesPerLine 图像每行锁占用的字节数
(5)Data 存储图像数据的指针
(6)Format 图像的格式
2.我们同样还需要实现和处理该图像类的方法,常用方法如下:
1.一个没有输入参数的构造函数,构造一个空的图像类
2.输入参数为 data,width,height,format的构造函数
3.由于我的整个教程是基于Qt的,所以还需要一个将QImage转化为MyImage的构造函数
4.将MyImage转化为QImage的函数
三、详细步骤:
接下来我们就来实现我们的图像类:
1.首先定义一个图像格式的枚举类型:
public: enum format{ GRAY8, RGB32, EMPTY };
2.在MyImage的定义中定义如下属性:
public: int m_width; int m_height; int m_nBitCount; int m_bytesPerLine; enum format m_format; unsigned char* m_data;
3.然后定义该类的方法
public: MyImage(); MyImage(unsigned char* data,int width,int height,enum format fmt); MyImage(MyImage* Scr); MyImage(const QImage &qimage); ~MyImage(); static QImage* MyImage2QImage(const MyImage &myimage);
4.以上方法的实现如下:
MyImage::MyImage() { m_width = 0; m_height = 0; m_nBitCount = 0; m_bytesPerLine = 0; m_data = NULL; m_format = format::EMPTY; } MyImage::MyImage(unsigned char *data, int width, int height, enum format fmt) { m_width = width; m_height = height; m_format = fmt; switch(fmt) { case format::GRAY8: m_nBitCount = 8; break; case format::RGB32: m_nBitCount = 32; break; } m_bytesPerLine = (width*m_nBitCount +31)/32*4; m_data = new unsigned char[m_bytesPerLine*height]; memcpy(m_data,data,m_bytesPerLine*height); } MyImage::MyImage(MyImage *Scr) { m_width = Scr->m_width; m_height = Scr->m_height; m_nBitCount = Scr->m_nBitCount; m_bytesPerLine = Scr->m_bytesPerLine; m_format = Scr->m_format; m_bytesPerLine = (m_width*m_nBitCount +31)/32*4; m_data = new unsigned char[m_bytesPerLine*m_height]; memcpy(m_data,Scr->m_data,m_bytesPerLine*m_height); } MyImage::MyImage(const QImage &qimage) { m_width = qimage.width(); m_height = qimage.height(); m_nBitCount = qimage.byteCount(); m_bytesPerLine = qimage.bytesPerLine(); if(qimage.format()==QImage::Format_RGB32) m_format = format::RGB32; else if(qimage.format()==QImage::Format_Grayscale8) m_format = format::GRAY8; m_data = new unsigned char[m_bytesPerLine*m_height]; memcpy(m_data,qimage.bits(),m_bytesPerLine*m_height); } MyImage::~MyImage() { if(m_data != NULL) delete m_data; } QImage* MyImage::MyImage2QImage(const MyImage &myimage) { QImage *qimage; if(myimage.m_format == MyImage::format::GRAY8) { qimage = new QImage(myimage.m_data, myimage.m_width, myimage.m_height, myimage.m_bytesPerLine, QImage::Format_Grayscale8); } else if(myimage.m_format == MyImage::format::RGB32) { qimage = new QImage(myimage.m_data, myimage.m_width, myimage.m_height, myimage.m_bytesPerLine, QImage::Format_RGB32); } return qimage; }
至此,我们的图像处理类就实现完成了
如果上述教程或代码中有任何错误,欢迎批评和指证。