#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(ui->openButton,SIGNAL(clicked()),this,SLOT(openFileSlot()));
QObject::connect(ui->cannyButton,SIGNAL(clicked()),this,SLOT(cannySlot()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::openFileSlot()
{
openFileName=QFileDialog::getOpenFileName(this,"打开文件",QDir::currentPath());
if(! ( img.load(openFileName) ) )
{
QMessageBox::information(this,
"打开图像失败",
"打开图像失败!");
return;
}
if((img.width()/img.height())>(ui->srcLabel->width()/ui->srcLabel->height()))
scaleImg = img.scaledToWidth(ui->srcLabel->width(),Qt::FastTransformation);
else
scaleImg = img.scaledToHeight(ui->srcLabel->height(),Qt::FastTransformation);
ui->srcLabel->setPixmap(QPixmap::fromImage(scaleImg));
}
void MainWindow::cannySlot()
{
if(openFileName.isEmpty())
{
QMessageBox::information(this,"警告!","没图片算个卵!");
return;
}
Mat matImg = QImage2cvMat(img);
Mat matImgGray,edge;
cvtColor(matImg,matImgGray,COLOR_RGB2GRAY);
blur(matImgGray,edge,Size(3,3));
Canny(edge,edge,20,60,3);
if((img.width()/img.height())>(ui->dstLabel->width()/ui->dstLabel->height()))
scaleImg = img.scaledToWidth(ui->dstLabel->width(),Qt::FastTransformation);
else
scaleImg = img.scaledToHeight(ui->dstLabel->height(),Qt::FastTransformation);
ui->dstLabel->setPixmap(QPixmap::fromImage(scaleImg));
}
Mat MainWindow::QImage2cvMat(QImage image)
{
cv::Mat mat;
qDebug() << image.format();
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_BGR2RGB);
break;
case QImage::Format_Indexed8:
mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());
break;
}
return mat;
}
QImage MainWindow::cvMat2QImage(const cv::Mat& mat)
{
if(mat.type() == CV_8UC1)
{
QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
image.setColorCount(256);
for(int i = 0; i < 256; i++)
{
image.setColor(i, qRgb(i, i, i));
}
uchar *pSrc = mat.data;
for(int row = 0; row < mat.rows; row ++)
{
uchar *pDest = image.scanLine(row);
memcpy(pDest, pSrc, mat.cols);
pSrc += mat.step;
}
return image;
}
else if(mat.type() == CV_8UC3)
{
const uchar *pSrc = (const uchar*)mat.data;
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
return image.rgbSwapped();
}
else if(mat.type() == CV_8UC4)
{
qDebug() << "CV_8UC4";
const uchar *pSrc = (const uchar*)mat.data;
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
return image.copy();
}
else
{
qDebug() << "ERROR: Mat could not be converted to QImage.";
return QImage();
}
}