根据您的代码,您正在创建一个 MainWindow 类型的新对象:
[...]
ui(new Ui::SecondDialog)
{
ui->setupUi(this);
MainWindow object;
[...]
这有空的grayImage
属性,这样你就会得到这种行为。
另一个问题是您使用的格式,您必须更改QImage::Format_RGB888
to QImage::Format_Indexed8
.
Format_RGB888:图像使用24位RGB格式(8-8-8)存储。
Format_Indexed8:使用 8 位索引将图像存储到颜色图中。
您要做的就是创建一个 setter 方法并将图像传递到新窗口,为此您必须执行以下操作:
第二个对话框.h
public:
void setImage(const Mat &image);
第二个对话框.c++
SecondDialog::SecondDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SecondDialog)
{
ui->setupUi(this);
}
void SecondDialog::setImage(const Mat &image){
QImage dest((const uchar *) image.data, image.cols, image.rows, image.step, QImage::Format_Indexed8);
ui->label_img->setPixmap(QPixmap::fromImage(dest));
}
所以最后你应该在 MainWindow.cpp 中运行以下代码:
void MainWindow::on_Browse_clicked()
{
QFileDialog dialog(this);
dialog.setNameFilter(tr("Images (*.png *.xpm *.jpg)"));
dialog.setViewMode(QFileDialog::Detail);
fileName = QFileDialog::getOpenFileName(this,
tr("Open Images"), "/home/rpi/Desktop/Picture/Sample Pictures", tr("Image Files (*.png *.jpg *.bmp)"));
if (!fileName.isEmpty())
{
String image_path=fileName.toLocal8Bit().constData();
Mat image= imread(image_path);
cvtColor(image, grayImage, CV_BGR2GRAY);
SecondDialog obj;
obj.setImage(grayImage);
obj.setModal(true);
obj.exec();
}
}
Edit:
就我而言,我使用以下函数来进行转换cv::Mat
to QImage
:
# https://github.com/eyllanesc/Mirosot-Peru/blob/master/Mirosot-PC/MatToQImage.cpp
QImage MatToQImage(const cv::Mat& mat)
{
// 8-bits unsigned, NO. OF CHANNELS=1
if(mat.type()==CV_8UC1)
{
// Set the color table (used to translate colour indexes to qRgb values)
QVector<QRgb> colorTable;
for (int i=0; i<256; i++)
colorTable.push_back(qRgb(i,i,i));
// Copy input Mat
const uchar *qImageBuffer = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_Indexed8);
img.setColorTable(colorTable);
return img;
}
// 8-bits unsigned, NO. OF CHANNELS=3
if(mat.type()==CV_8UC3)
{
// Copy input Mat
const uchar *qImageBuffer = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
return img.rgbSwapped();
}
else
{
qDebug() << "ERROR: Mat could not be converted to QImage.";
return QImage();
}
} // MatToQImage()