2017-06-15 140 views
0

使用opencv顯示圖像時,我總是會看到一個灰色的屏幕,圖像是從攝像頭捕獲的。任何幫助?從攝像頭獲取輸入opencv C++

#include "stdafx.h" 
#include <opencv2\opencv.hpp> 
#include <opencv2\imgcodecs.hpp> 

using namespace cv; 

cv::Mat takePicture() { 
cv::Mat pic; 
VideoCapture cam(0); 
while (!cam.isOpened()) { 
    std::cout << "Failed to make connection to cam" << std::endl; 
    VideoCapture cam(0); 
} 
cam >> pic; 
return pic; 
} 
int main() 
{ 

cv::Mat pic1; 

pic1 = takePicture(); 

imshow("camera", pic1); 

} 
+0

您需要使用['waitKey()'](http://docs.opencv.org/2.4/modules/highgui/doc/user_interface.html? highlight = waitkey#waitkey)在使用'imshow()'讓圖像顯示在窗口中後。更多[這裏](https://stackoverflow.com/questions/12452118/what-does-waitkey-30-mean-in-opencv)。但這可能不是你的問題。我已經將此標記爲重複的,因爲之前已經提出過,並且有答案。 –

+3

[OpenCV - Webcam imshow可能不會顯示實時動態,灰色屏幕替代](https://stackoverflow.com/questions/43726804/opencv-webcam-imshow-not-displaying-live-feed-gray-screen-instead ) –

+0

@AlexanderReynolds謝謝!解決了我的問題。 –

回答

0

相機需要時間進行初始化。 也許你應該改變你的代碼是這樣的:

#include "stdafx.h" 
#include <opencv2\opencv.hpp> 
#include <opencv2\imgcodecs.hpp>  
VideoCapture cam(0); 
cv::Mat pic; 
cv::Mat takePicture(){ 
    while (!cam.isOpened()) { 
     std::cout << "Failed to make connection to cam" << std::endl; 
     cam.open(0); 
    } 
    cam>>pic; 
    return pic; 
} 
int main(){ 
    cv::waitKey(1000); 
    cv::Mat pic1; 
    pic1 = takePicture(); 
    imshow("camera", pic1); 
    cv::waitKey(); 
}