QImage to cv :: Mat转换奇怪的行为与imread

时间:2016-11-25 12:47:17

标签: c++ linux qt opencv

我必须将QImage转换为cv :: Mat,如果我使用similar topics中描述的技术,我会收到不同数量的轮廓(7--8)和奇怪的结果矩阵,但如果我这样做

QImage im;
im.save ("tmp.bmp");
cv::Mat rImage;
rImage = cv::imread ("tmp.bmp", CV_LOAD_IMAGE_GRAYSCALE);

函数findContours工作正常。这些技术之间的区别是什么?我可以在这些方法之间存档相同的结果?

2 个答案:

答案 0 :(得分:0)

Your code works for me.

int main(int argc, char *argv[]){
    QImage img(QString("lena.bmp"));
    QImage img2 = img.convertToFormat(QImage::Format_RGB32);
    cv::Mat imageMat = qimage_to_cvmat_copy(img2, CV_8UC4);
    cv::namedWindow("lena");
    cv::imshow("lena", imageMat);
    cv::waitKey(0);
}
cv::Mat qimage_to_cvmat_copy(const QImage &img, int format)
{
    uchar* b = const_cast<uchar*> (img.bits ());
    int c = img.bytesPerLine();
    return cv::Mat(img.height(), img.width(), format, b, c).clone();
}

Make sure your Mat format is CV_8UC4 if your QImage format is Format_RGB32. You don't have to do a cvtColor or mixChannels.

答案 1 :(得分:0)

全部!

如上所述,我使用转换QImage转换为cv :: Mat,如here所述。我的源代码变成了这样的东西

QImage srcIm (argv[1]);
QImage img2 = srcIm.convertToFormat(QImage::Format_ARGB32);
Mat src_gray = QImageToCvMat (img2);
cvtColor (src_gray, src_gray1, CV_RGB2GRAY);

Mat bwimg = src_gray1.clone();// > 127;
vector<vector<Point> > contours;

findContours( bwimg, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE );    

一切正常。