Qt OpenCV 学习(五):答题线识别
2023-12-14 16:33:23
1. mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <opencv2/opencv.hpp>
#include <QString>
#include <QPixmap>
#include <QDebug>
#include <QImage>
#include <QFileDialog>
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);
}
文章来源:https://blog.csdn.net/qq_42994487/article/details/134865783
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!