qt+opencv实现拍照,打开视频,图像处理操作

最近小博甚是堕落,在做深度学习好久没有啥进展,哎,人生最苦莫过于程序员啊,今天这篇文章就来和大家一起学学QT吧,下面我用QT实现摄像头的拍照,录像,以及打开视频文件,图像处理等操作
qt主要是用来做界面设计,opencv主要用来做算法处理。程序开发之前我们需要来讲下配置工作
硬件环境 ubuntu14.04+opencv3.10+qt5.7
软件:qtcreator

ubuntu 安装opencv我早已经提过n次了,在这里我提一下如何最简单的安装一下qt5吧,同样四句命令就OK

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install qt5-default
sudo apt-get install qtcreator

安装完成在安装程序中就可以打开了,qt的配置请自行百度了
我们拖动6个按钮和一个Label到对话框里,分别将他们名字按图修改,然后对着每个按钮右键,点击go to slot,也就是点击按钮时所触发的函数。
qt+opencv实现拍照,打开视频,图像处理操作_第1张图片

当你点击玩go to slot之后你会发现到在MainWindow中,你的按钮函数已经声明,所以说真的好简单。我贴下我的代码结构,方便菜鸟学习。
qt+opencv实现拍照,打开视频,图像处理操作_第2张图片
编写打开和关闭摄像头的代码,使摄像头的视频图像以及图片和文件视频的播放都在在“输入视频”label中显示。接下来我直接贴出代码让大家学习下吧。大家对照代码结构copy
1这是.pro文件pro文件就是对界面的所用到的库的路径进行配置。

#-------------------------------------------------
#
# Project created by QtCreator 2017-09-06T15:42:56
#
#-------------------------------------------------

QT       += core gui multimediawidgets multimedia

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
QMAKE_CXXFLAGS += -std=c++0x

TARGET = opentest
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui


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


LIBS += `pkg-config opencv --cflags --libs`

mainwindow.h文件,这个文件是对所有类及其成员进行声明

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include 
#include
#include
#include 
#include 
#include 
#include 
#include
#include
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include 
#include 
#include

#include   //列表控件

#include  //列表控件条目
#include
using namespace cv;
using namespace std;
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
//protected:
protected:

   // void paintEvent(QPaintEvent *);

private slots:
    void nextFrame();
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();

    void on_pushButton_4_clicked();

    void on_pushButton_5_clicked();

    //void on_pushButton_6_clicked();

    void on_openimage_clicked();

private:
    Ui::MainWindow *ui;
    Mat frame;
    Mat  edges;
    VideoCapture capture;
    QImage image;
    QTime *timer;
    double rate;
    VideoWriter writer;
};

#endif // MAINWINDOW_H

main.cpp文件,这是当没有用到ui时所要编写代码的主函数,我在这里直接用的.ui,所以没有做任何修改,还是默认生成的。

#include "mainwindow.h"
#include 
#include
#include
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
   MainWindow w;
    w.show();
//QLabel label("hello world");
//QDebug()<<"ciclk me";
//label.show();
    return a.exec();
}

接下来是最重要的mainwindow.cpp了,所有代码都在这了,每个按钮所对应一个槽函数,不说了,上代码

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

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

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


QImage  Mat2QImage(cv::Mat cvImg)
{
    QImage qImg;
    if(cvImg.channels()==3)                             //3 channels color image
    {

        cv::cvtColor(cvImg,cvImg,CV_BGR2RGB);
        qImg =QImage((const unsigned char*)(cvImg.data),
                    cvImg.cols, cvImg.rows,
                    cvImg.cols*cvImg.channels(),
                    QImage::Format_RGB888);
    }
    else if(cvImg.channels()==1)                    //grayscale image
    {
        qImg =QImage((const unsigned char*)(cvImg.data),
                    cvImg.cols,cvImg.rows,
                    cvImg.cols*cvImg.channels(),
                    QImage::Format_Indexed8);
    }
    else
    {
        qImg =QImage((const unsigned char*)(cvImg.data),
                    cvImg.cols,cvImg.rows,
                    cvImg.cols*cvImg.channels(),
                    QImage::Format_RGB888);
    }

    return qImg;

}
void MainWindow::nextFrame()
{
    capture>>frame;
    if(!frame.empty())
    {
        image=Mat2QImage(frame);
        ui->label->setPixmap(QPixmap::fromImage(image));

    }


}

void MainWindow::on_pushButton_clicked()
{
    if (capture.isOpened())
            capture.release();     //decide if capture is already opened; if so,close it
        QString filename =QFileDialog::getOpenFileName(this,tr("Open Video File"),".",tr("Video Files(*.avi *.mp4 *.flv *.mkv)"));
        capture.open(filename.toLocal8Bit().data());
        if (capture.isOpened())
        {
            rate= capture.get(CV_CAP_PROP_FPS);
            capture >> frame;
            if (!frame.empty())
            {

                image = Mat2QImage(frame);
                ui->label->setPixmap(QPixmap::fromImage(image));
                QTimer *timer = new QTimer(this);
                timer->setInterval(1000/rate);   //set timer match with FPS
                connect(timer, SIGNAL(timeout()), this, SLOT(nextFrame()));
                timer->start();
            }
        }
}

void MainWindow::on_pushButton_2_clicked()
{
    if (capture.isOpened())
           capture.release();     //decide if capture is already opened; if so,close it
       capture.open(0);           //open the default camera
       if (capture.isOpened())
       {
           rate= capture.get(CV_CAP_PROP_FPS);
           capture >> frame;
           if (!frame.empty())
           {

               image = Mat2QImage(frame);
               ui->label->setPixmap(QPixmap::fromImage(image));
               QTimer *timer = new QTimer(this);
               timer->setInterval(1000/rate);   //set timer match with FPS
               connect(timer, SIGNAL(timeout()), this, SLOT(nextFrame()));
               timer->start();
           }
       }
}

void MainWindow::on_pushButton_3_clicked()
{
    cv::Mat cannyImg ;
    cv::Canny(frame, cannyImg, 0, 30, 3);
    cv::namedWindow("Canny");
    cv::imshow("Canny", cannyImg);
}

void MainWindow::on_pushButton_4_clicked()
{
    writer.open("./myrec.avi",cv::VideoWriter::fourcc('P','I','M','1'), /*capture.get(CV_CAP_PROP_FPS)*/30, cv::Size(frame.cols, frame.rows),true);
    int t=100; while(t--) {writer.write(frame);} //record 100 frames
    ui->pushButton_4->setDisabled(true); //if successfully start videoWriter, disable the button
}

void MainWindow::on_pushButton_5_clicked()
{
    writer.release();
}

//void MainWindow::on_pushButton_6_clicked()
//{
//    Mat image1;
//    cvtColor(frame,edges,CV_BGR2GRAY);//把图像转换为灰度图像
//    blur(edges,edges,Size(7,7));//模糊降噪
//    Canny(edges,edges,3,9,3);//Canny 边缘检测
//         image1 = Mat2QImage(edges);
//      ui->label->setPixmap(QPixmap::fromImage(image1));

//    QTimer *timer = new QTimer(this);
//    timer->setInterval(1000/rate);   //set timer match with FPS
//    connect(timer, SIGNAL(timeout()), this, SLOT(nextFrame()));
//    timer->start();
//}

void MainWindow::on_openimage_clicked()
{
//       Mat image = imread("1.jpg");
//       QImage frame = Mat2QImage(image);
//        ui->label->setPixmap(QPixmap::fromImage(frame));
//        复制代码

            QString filename;
            filename=QFileDialog::getOpenFileName(this,
                                                  tr("选择图像"),
                                                  "",
                                                  tr("Images (*.png *.bmp *.jpg *.tif *.GIF )"));
            if(filename.isEmpty())
            {
                 return;
            }
            else
            {
                QImage* img=new QImage;

                if(! ( img->load(filename) ) ) //加载图像
                {
                    QMessageBox::information(this,
                                             tr("打开图像失败"),
                                             tr("打开图像失败!"));
                    delete img;
                    return;
                }
                ui->label->setPixmap(QPixmap::fromImage(*img));
            }
}

最后我们贴出我的效果图吧,没有做任美化,有点小丑,大奖将就着看吧,哈哈。。。
qt+opencv实现拍照,打开视频,图像处理操作_第3张图片
qt+opencv实现拍照,打开视频,图像处理操作_第4张图片

你可能感兴趣的:(写给大家看的C++,图像处理)