天天看點

OpenCV啟動攝像頭

July 28, 2016

作者:dengshuai_super

出處:http://blog.csdn.net/dengshuai_super/article/details/52057828

聲明:轉載請注明作者及出處。

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>

using namespace cv;


int main()
{
    VideoCapture cap();
    if(!cap.isOpened())
    {
        return -;
    }
    Mat frame;
    Mat edges;

    bool stop = false;
    while(!stop)
    {
        cap>>frame;
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(,), , );
        Canny(edges, edges, , , );
        imshow("目前視訊",edges);
        if(waitKey() >=)
            stop = true;
    }
    return ;
}
           

對代碼的幾點說明:

1. VideoCapture類有兩種用法,一種是VideoCapture(const string& filename)用來打開視訊檔案,一種是VideoCapture(int device)用來打開裝置。

2. isOpened函數用來檢測VideoCapture類是否打開成功。

3. C++版本的OpenCV有一個明顯的好處,就是不需要釋放操作(不論是視訊還是圖檔),VideoCapture類的析構函數會自動幫你完成。

下面這段程式是打開攝像頭并顯示攝像頭的。

#include <cv.h>
#include <cxcore.h>
#include <highgui.h>

int main( int argc, char** argv )
{
    //聲明IplImage指針
    IplImage* pFrame = NULL;

    //擷取攝像頭
    CvCapture* pCapture = cvCreateCameraCapture(-);

    //建立視窗
    cvNamedWindow("video", );

    //顯示視屏
    while()
    {
        pFrame=cvQueryFrame( pCapture );
        if(!pFrame)break;
        cvShowImage("video",pFrame);
        char c=cvWaitKey();//讓每一幀暫停33ms
        if(c==)break; //ESC,ASCⅡ碼27回車,ASCⅡ碼13換行(Ctrl + Enter),ASCⅡ碼10空格,ASCⅡ碼32
    }
    cvReleaseCapture(&pCapture);
    cvDestroyWindow("video");
}
           

在Macbook pro 上,上面兩段代碼我都可以跑通,都可以調取自帶的攝像頭。

攝像頭可以在系統資訊—>相機 檢視:

FaceTime 高清相機(内建):

  型号 ID:    UVC Camera VendorID_1452 ProductID_34057
  唯一 ID:    0x1a11000005ac8509
           

UVC,全稱為:USB video class 或USB video device class。是Microsoft與另外幾家裝置廠商聯合推出的為USB視訊捕獲裝置定義的協定标準,目前已成為USB org标準之一。是以就相當于調用USB攝像頭了。