1. 程式人生 > >qt+opencv實現拍照,開啟視訊,影象處理操作

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,也就是點選按鈕時所觸發的函式。
這裡寫圖片描述

當你點選玩go to slot之後你會發現到在MainWindow中,你的按鈕函式已經宣告,所以說真的好簡單。我貼下我的程式碼結構,方便菜鳥學習。
這裡寫圖片描述
編寫開啟和關閉攝像頭的程式碼,使攝像頭的視訊影象以及圖片和檔案視訊的播放都在在“輸入視訊”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<opencv2/opencv.hpp>
#include<QtGui>
#include <QMainWindow>
#include<QFileDialog>
#include<QLabel>
#include <QWidget>
#include <QImage>
#include <QTimer>
#include <QTime>
#include<QTimerEvent>
#include<QTimeEdit>
#include <QImage>
#include <QDialog>
#include <QColor>
#include <QDir>
#include <QDebug>
#include <QIcon>
#include <QPalette>
#include <QListWidget>
#include<QWidget>
#include<QPushButton>
#include<QToolButton>
#include<QMediaPlayer>
#include<QMediaPlaylist>
#include<QListView>
#include<QHBoxLayout>
#include<QVBoxLayout>
#include<QStringListModel>
#include<QSlider>
#include<QStackedWidget>
#include<QKeyEvent>
#include<QLabel>
#include <QWidget>
#include <QVideoWidget>
#include<QMessageBox>

#include <QListWidget>  //列表控制元件

#include <QListWidgetItem> //列表控制元件條目
#include<QtGui/QTouchEvent>
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 <QApplication>
#include<QLabel>
#include<QDebug>
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));
            }
}

最後我們貼出我的效果圖吧,沒有做任美化,有點小丑,大獎將就著看吧,哈哈。。。
這裡寫圖片描述
這裡寫圖片描述