cpp
复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::showImage(Mat &sendMat) {
Mat showImg = sendMat.clone();
if (showImg.channels() == 1) {
QImage showPic = QImage((const unsigned char*)(showImg.data), showImg.cols, showImg.rows, showImg.step, QImage::Format_Indexed8);
ui->labelShow->setPixmap(QPixmap::fromImage(showPic.scaled(ui->labelShow->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)));
} else if (showImg.channels() == 3) {
QImage showPic = QImage((const unsigned char*)(showImg.data), showImg.cols, showImg.rows, showImg.step, QImage::Format_RGB888);
ui->labelShow->setPixmap(QPixmap::fromImage(showPic.scaled(ui->labelShow->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)));
}
}
void MainWindow::on_btnOpn_clicked() {
ui->lineEdit->clear();
ui->labelShow->clear();
QString filePath = QFileDialog::getOpenFileName(this, "open picture", ".", "picture (*.png *.jpg *.bmp)); All files (*.*)");
ui->lineEdit->setText(filePath);
srcImg = imread(filePath.toStdString());
ui->labelShow->clear();
showImage(srcImg);
}
void MainWindow::on_btn_clicked() {
Mat grayImg, binaryImg, morhpImg;
cvtColor(srcImg, grayImg, COLOR_BGR2GRAY);
threshold(grayImg, binaryImg, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
Mat kernel = getStructuringElement(MORPH_RECT, Size(20, 1), Point(-1, -1));
morphologyEx(binaryImg, morhpImg, MORPH_OPEN, kernel, Point(-1, -1));
kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
dilate(morhpImg, morhpImg, kernel);
// hough lines
vector<Vec4i>lines;
HoughLinesP(morhpImg, lines, 1, CV_PI / 180.0, 5, 10, 5);
Mat resultImg = srcImg.clone();
cvtColor(resultImg, resultImg, COLOR_BGR2RGB);
for (size_t i = 0; i < lines.size(); i++) {
Vec4i ln = lines[i];
line(resultImg, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(0, 255, 255), 2, LINE_AA);
}
showImage(resultImg);
}