在涉及到QT和OpenCV的联合开发过程中,经常需要使用到在QT界面中显示图像的操作,但由于官方库并不存在互转函数,需要我们根据图片类型自行转换格式。转换函数如下:
CvMat转QImage函数
QPixmap CvMat2QImage(cv::Mat& img)
QPixmap CvMat2QImage(cv::Mat& img)
{
if (img.depth() != CV_8U){
cv::Mat tmpImg;
if (img.depth() == CV_8S){
img.convertTo(tmpImg, CV_8UC(img.channels()), 1, 128);
}
else if (img.channels() == 1){
double maxVal, minVal;
cv::minMaxLoc(img, &minVal, &maxVal);
double t = 255 / (maxVal - minVal);
img.convertTo(tmpImg, CV_8UC(img.channels()), t, -minVal * t);
}
else{
assert(false);
}
if (tmpImg.empty() == false){
img = tmpImg;
}
}
QImage qimg;
cv::Mat cvtImg;
int nType = img.type();
int nStep = img.step;
switch (img.type())
{
case CV_8UC1:
qimg = QImage(img.data, img.cols, img.rows, img.step, QImage::Format_Grayscale8);
break;
case CV_8UC3:
cv::cvtColor(img, cvtImg, cv::COLOR_BGR2RGB);
qimg = QImage(cvtImg.data, cvtImg.cols, cvtImg.rows, cvtImg.step, QImage::Format_RGB888);
break;
case CV_8UC4:
cvtImg = img;
qimg = QImage(cvtImg.data, cvtImg.cols, cvtImg.rows, cvtImg.step, QImage::Format_RGB32);
break;
default:
qimg = QImage(img.data, img.cols, img.rows, img.step, QImage::Format_Grayscale8);
break;
}
return QPixmap::fromImage(std::move(qimg));
}
CvMat转QImage函数
cv::Mat QImage2cvMat(QImage image)
cv::Mat QImage2cvMat(QImage image)
{
cv::Mat mat;
switch (image.format())
{
case QImage::Format_ARGB32:
case QImage::Format_RGB32:
case QImage::Format_ARGB32_Premultiplied:
mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine());
break;
case QImage::Format_RGB888:
mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine());
cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB);
break;
case QImage::Format_Indexed8:
case QImage::Format_Grayscale8:
mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());
break;
default:
break;
}
return mat;
}