Qt OpenCV 学习(五):答题线识别

Qt OpenCV 学习(五):答题线识别_第1张图片

1. mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 

#include 
#include 
#include 
#include 
#include 

using namespace cv;
using namespace std;

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    void showImage(Mat &sendMat);

private slots:
    void on_btnOpn_clicked();

    void on_btn_clicked();

private:
    Ui::MainWindow *ui;

    Mat srcImg;
};
#endif // MAINWINDOW_H

2. mainwindow.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);
}

你可能感兴趣的:(Qt,OpenCV,学习,qt,opencv,学习)