2014-02-20 13 views
0

爲了使我的問題更加清楚,請查看下面的下面的代碼:cvReleaseCapture()錯誤

抓拍圖像:

void CameraTest ::on_snapButton_clicked() 
{ 
    CvCapture* capture = cvCaptureFromCAM(0); // capture from video device #0 


    cvSetCaptureProperty(capture ,CV_CAP_PROP_FRAME_WIDTH , 800); 
    cvSetCaptureProperty(capture ,CV_CAP_PROP_FRAME_HEIGHT , 600); 


    if(!cvGrabFrame(capture)) //if no webcam detected or failed to capture anything 
    {    // capture a frame 
     cout << "Could not grab a frame\n\7"; 
     exit(0); 
    } 

    IplImage* img=cvRetrieveFrame(capture);   // retrieve the captured frame 

    cv::Mat imageContainer(img); 
    image=imageContainer; 
    cv::imshow("Mat",image); 

    //cvReleaseCapture(&capture); When I enable this, and run the programming calling this, there will be an error. 
} 

現在,程序顯示的圖像:

 void CameraTest ::on_processButton_clicked() 
     { 
      cv::imshow("image snapped", image); 

      //my image processing steps... 
     } 

當我啓用cvReleaseCapture(&capture)線,我收到以下錯誤:

Unhandled exception at 0x00fc3ff5 in CameraTest.exe: 0xC0000005: Access violation reading location 0x042e1030. 

當我評論/刪除行,我能夠正確後點擊另一個按鈕來顯示圖像,但是當我要拍攝的新圖像,我必須按一下按鈕幾次,這是一個重大的安全漏洞存在於程序。無論如何要繞過它嗎?

回答

2
  • 避免過時的c-api(IplImages,Cv *功能)堅持使用C++ api。
  • 圖像從捕捉點到內存裏面凸輪驅動器獲得。如果你不克隆()圖像,並釋放捕獲,你會得到一個懸掛指針。
  • 不會爲每個鏡頭創建新的捕捉。 (凸輪需要一些「熱身」時間,所以它會像地獄一樣緩慢)。 保持周圍一個實例在你的類,而不是

class CameraTest 
{ 
    VideoCapture capture;   // make it a class - member 
    CameraTest() : capture(0) // capture from video device #0 
    { 
     capture.set(CV_CAP_PROP_FRAME_WIDTH , 800); 
     capture.set(CV_CAP_PROP_FRAME_HEIGHT , 600); 
    } 

    // ... 
}; 

void CameraTest ::on_snapButton_clicked() 
{ 
    Mat img;    // temp var pointing todriver mem  

    if(!capture.read(img)) //if no webcam detected or failed to capture anything 
    { 
     cout << "Could not grab a frame\n\7"; 
     exit(0); 
    } 

    image = img.clone();  // keep our member var alive 
    cv::imshow("Mat",image); 

} 
+0

Thanks @Berak!它的工作,加上一個,併爲你接受答案。欣賞它( – rockinfresh

1

替換:

if(!cvGrabFrame(capture)) //if no webcam detected or failed to capture anything 
    {    // capture a frame 
     cout << "Could not grab a frame\n\7"; 
     exit(0); 
    } 

通過

if (!capture) 
     { 
      cout << "Could not grab a frame\n\7"; 
      exit(0); 

     } 

並更換

IplImage* img=cvRetrieveFrame(capture); 

通過

IplImage* img = cvQueryFrame(capture); 

cvQueryFrame收藏,並返回從視頻或相機的幀。該函數在一次調用中是cvGrabFrame和cvRetrieveFrame的combination。返回的圖像不應該被用戶釋放或修改。

+0

)不起作用,但對於該建議+1,請欣賞它。 – rockinfresh