【发布时间】:2015-11-14 19:45:35
【问题描述】:
我正在开发 Visual Studio 2010 C++ 和 Opencv 2.3.1。使用 HP 笔记本电脑 windows 7 32 位。我真的尝试过很多次来解决这个问题,但它仍然在发生。我的内置网络摄像头带有一些代码(有时有效,有时无效),而对于其他一些代码,它总是显示灰色窗口而不是摄像头供稿?
有人可以帮忙吗?
提前致谢。
例如第一个代码有时显示凸轮进给,第二个代码总是显示灰色窗口
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if (!cap.isOpened()) // check if we succeeded
return -1;
Ptr<BackgroundSubtractor> pMOG = new BackgroundSubtractorMOG2();
Mat fg_mask;
Mat frame;
int count = -1;
for (;;)
{
// Get frame
cap >> frame; // get a new frame from camera
// Update counter
++count;
// Background subtraction
pMOG->operator()(frame, fg_mask);
imshow("frame", frame);
imshow("fg_mask", fg_mask);
// Save foreground mask
string name = "mask_" + std::to_string(static_cast<long long>(count)) + ".png";
imwrite("D:\\SO\\temp\\" + name, fg_mask);
if (waitKey(1) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
///////////////////// 第二个代码:
// WriteVideo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char* argv[])
{
VideoCapture cap(0); // open the video camera no. 0
if (!cap.isOpened()) // if not success, exit program
{
cout << "ERROR: Cannot open the video file" << endl;
return -1;
}
namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video
cout << "Frame Size = " << dWidth << "x" << dHeight << endl;
Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));
VideoWriter oVideoWriter ("D:/visual outs/mix/WriteVideo.avi", CV_FOURCC('P','I','M','1'), 20, frameSize, true); //initialize the VideoWriter object
if ( !oVideoWriter.isOpened() ) //if not initialize the VideoWriter successfully, exit the program
{
cout << "ERROR: Failed to write the video" << endl;
return -1;
}
while (1)
{
Mat frame;
bool bSuccess = cap.read(frame); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "ERROR: Cannot read a frame from video file" << endl;
break;
}
oVideoWriter.write(frame); //writer the frame into the file
imshow("MyVideo", frame); //show the frame in "MyVideo" window
if (waitKey(10) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
【问题讨论】:
-
哪些代码?您能否详细说明并添加一些代码?
-
感谢@Miki,现在我添加了 2 个代码
-
我工作正常。尝试删除与
VideoWriter相关的代码。问题可能就在于此。 -
两者都正常工作?
-
第二个没有 VideoWriter 的东西,可能我缺少一些编解码器。检查它是否也适用于没有 VideoWritere 的东西。如果是这样,您就知道问题出在哪里了。