opencv调用摄像头

时间:2021-11-28 20:11:13

这种方法很基础,博主也用了很多次了,不过为了防止自己忘记还是mark一下

#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <string>
#include <sstream>
#include <Windows.h>

using namespace std;
using namespace cv;
string num2str(int i){
stringstream s;
s<<i;
return s.str();
}
int main( int argc, char** argv )
{
//保存图像位置
string ss("");
//mkdir(ss.c_str());
//声明IplImage指针
cv::VideoCapture videoCapture(0);
//cout << videoCapture.isOpened() << endl;
videoCapture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
videoCapture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
//videoCapture.set(CV_CAP_PROP_EXPOSURE, 0.0001);
//videoCapture.set(CV_CAP_PROP_GAIN, 1);
Mat intrinsic = (Mat_<double>(3, 3) << 392.6625 , 0 , 593.9263,
0 , 390.7315 , 329.4303,
0 , 0 , 1.0000);
Mat distortion = (Mat_<double>(4, 1) << -0.204700391393686, 0.0298622006125642, 0.00612432307199318, 0.000947722538938783);
Mat frame;
Mat distortframe;
int index=0;
//显示视屏
char c=0;
while(1)
{
videoCapture >> frame;
if (!frame.data)
continue;
Mat gray;
cvtColor(frame, gray, CV_RGB2GRAY);
undistort(frame, distortframe, intrinsic, distortion);
imshow("video", frame);
//imshow("disvideo", distortframe);
if (c == 32){ //c==32
imwrite((num2str(index) + ".jpg").c_str(), frame);
cout<<index<<endl;
++index;
//Sleep(2000);
}

c=cvWaitKey(30);
//cout<<int(c)<<endl;
if(c==27)break;
}
cvDestroyWindow("video");
};

博主加入了按空格键存储图片,按esc退出的功能