2013-11-20 29 views
0

我正在使用OpenCV 2.4.6。我在互聯網上找到了一些從相機獲取幀的例子。它運作良好(它將我醜陋的臉部顯示在屏幕上)。但是,我絕對無法從幀中獲取像素數據。我在這裏找到了一些主題:http://answers.opencv.org/question/1934/reading-pixel-values-from-a-frame-of-a-video/但它不適用於我。OpenCV - 從相機設備獲取像素數據

這裏是代碼 - 在評論部分我指出了什麼是錯的。

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

using namespace cv; 

int main() { 
    int c; 
    IplImage* img; 
    CvCapture* capture = cvCaptureFromCAM(1); 
    cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); 
    while(1) { 
     img = cvQueryFrame(capture); 

     uchar* data = (uchar*)img->imageData; // access violation 

     // this does not work either 
     //Mat m(img); 
     //uchar a = m.data[0]; // access violation 

     cvShowImage("mainWin", img); 
     c = cvWaitKey(10); 
     if(c == 27) 
      break; 
    } 
} 

您能給我一些建議嗎?

回答

2

我建議使用較新的Mat結構而不是IplImage,因爲您的問題是用C++標記標記的。對於您的任務,您可以使用Matdata成員 - 它指向內部Mat存儲。例如Mat img; uchar* data = img.data;。這裏有一個完整的例子

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

using namespace cv; 

int main() { 
    int c; 
    Mat img; 
    VideoCapture capture(0); 
    namedWindow("mainWin", CV_WINDOW_AUTOSIZE); 
    bool readOk = true; 

    while(capture.isOpened()) { 

     readOk = capture.read(img); 

     // make sure we grabbed the frame successfully 
     if (!readOk) { 
      std::cout << "No frame" << std::endl; 
      break; 
     } 

     uchar* data = img.data; // this should work 

     imshow("mainWin", img); 
     c = waitKey(10); 
     if(c == 27) 
      break; 
    } 
} 
+0

它拋出(即使我刪除UCHAR *數據...部分)的Microsoft C++異常:CV ::異常內存位置0x002BF794並打開throw.cpp文件(指着最後一行文件)在Visual Studio 2012. :( – tobi

+0

嗯..這在我的系統上運行良好,沒有例外拋出。你是否使用'cv :: Mat'而不是像'IplImage'那樣的例子? – Alexey

+0

是的,我喜歡。從我看到的,當我刪除imshow()它不會拋出任何異常,但顯然我沒有看到任何圖像。 – tobi