qt-opencv图像增强之梯度提取

qt-opencv图像增强之梯度提取

  • 1 .pro项目文件配置
  • 2 ui设计
  • 3 使用Sobel算子
  • 4 mainwindow.cpp代码
  • 5 运行结果

1 .pro项目文件配置

添加

INCLUDEPATH += /usr/local/include \
                /usr/local/include/opencv
                /usr/local/include/opencv2

LIBS += /usr/local/lib/libopencv_* \

2 ui设计

左边是原始rgb图像,右边是梯度图像。下面两个按钮,一个是打开摄像头,一个是退出。

3 使用Sobel算子

竖直方向的梯度Sobel算子

-1 -2 -1
0 0 0
1 2 1

水平方向的梯度Sobel算子

-1 0 1
-2 0 2
-1 0 1

相关函数调用了opencv的函数,不想造轮子了,累!

4 mainwindow.cpp代码

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
#include

using namespace cv;

void mat2qimg(Mat &src,QImage &qimg);//Mat转QImage
void getGradMat(Mat &src,Mat &dst);//获得gradient matrix

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //打开摄像头
    connect(ui->openCamBtn,&QPushButton::clicked,this,[=](){
        VideoCapture capture(0);


        QImage qimgf,qimgg;

        int rows = ui->rgbLabel->height();
        int cols = ui->rgbLabel->width();

        Mat frame;
        Mat grad = Mat::zeros(rows,cols,CV_8UC1);

        while (1)
        {
            capture >> frame;
            cv::resize(frame,frame,Size(cols,rows));

            getGradMat(frame,grad);//梯度函数

            mat2qimg(frame,qimgf);
            mat2qimg(grad,qimgg);//梯度图像

            ui->rgbLabel->setPixmap(QPixmap::fromImage(qimgf));
            ui->gradLabel->setPixmap(QPixmap::fromImage(qimgg));

            waitKey(20);
        }
    });


    //退出
    connect(ui->closeBtn,&QPushButton::clicked,this,[=](){
        exit(0);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void mat2qimg(Mat &src,QImage &qimg)
{
    if (src.channels()==3)
    {
        cvtColor(src,src,CV_BGR2RGB);
        qimg = QImage((const unsigned char*)(src.data), src.cols, src.rows, QImage::Format_RGB888 );
    }
    else
    {
        qimg = QImage((const unsigned char*)(src.data), src.cols, src.rows, QImage::Format_Grayscale8 );
    }
    return;
}

void getGradMat(Mat &src,Mat &dst)
{
    int rows = src.rows;
    int cols = src.cols;
    int scale = 1;
    int delta = 0;
    int ddepth = CV_16S; //16位的有符号短整型short int类型


    //转成灰度图
    Mat src_gray;
    cvtColor( src, src_gray, CV_RGB2GRAY );

    Mat grad_x, grad_y;
    Mat abs_grad_x, abs_grad_y;
	//x方向梯度
    Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT );
    convertScaleAbs( grad_x, abs_grad_x );
	//y方向梯度
    Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT );
    convertScaleAbs( grad_y, abs_grad_y );
	//g = abs(gx)*0.5 + abs(gy)*0.5
    addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, dst);

}

5 运行结果

qt-opencv图像增强之梯度提取_第1张图片

你可能感兴趣的:(qt,opencv,ubuntu)