编写QT界面时,显示图像用Qt 自带的 QImage 类非常方便;
但是如果要对图像进行处理,首选的是Opencv库,这个时候就需要用到QImage 和 Opencv Mat 两种数据之间的转换。
void convertMattoQImage( Mat_<Vec3b>& img_cv, QImage &img_qt)
{
img_qt.convertFormat(QImage::Format_RGB32); // 将QImage 转换成32位格式 32位格式是最便于处理
image_qt.scaled(img_cv.rows, img_cv.cols);
int lineNum = 0;
int height = img_cv.rows;
int width = img_cv.cols;
uchar* imgBits = img_qt.bits(); // img_qt 的首字节地址
for( int i=0; i<height; i++ )
{
lineNum = i* width*4;
for(int j=0; j<width; j++)
{
imgBits[lineNum + j*4 + 2] = img_cv(i, j)[2];
imgBits[lineNum + j*4 + 1] = img_cv(i, j)[1];
imgBits[lineNum + j*4 + 0] = img_cv(i, j)[0];
}
}
}
}
void convertQImageToMat( QImage &img_qt, Mat_<Vec3b>& img_cv)
{
img_cv.create(img_qt.height(), img_qt.width());
img_qt.convertToFormat(QImage::Format_RGB32);
int lineNum = 0;
int height = img_qt.height();
int width = img_qt.width();
uchar *imgBits = img_qt.bits();
for(int i=0; i<height; i++)
{
lineNum = i* width *4;
for(int j=0; j<width; j++)
{
img_cv(i, j)[2] = imgBits[lineNum + j*4 + 2];
img_cv(i, j)[1] = imgBits[lineNum + j*4 + 1];
img_cv(i, j)[0] = imgBits[lineNum + j*4 + 0];
}
}
}