首先是c++版本:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv){
VideoCapture capture(0); //通过输入设备号控制采集使用的摄像头,一般0代表笔记本自带摄像头。
Mat frame,im;
capture >> frame; //将采集到的图像保存的frame
cvtColor(frame,im,CV_BGR2GRAY);
imwrite("capture.jpg",im);
imshow("pic",im);
waitKey(3000);
return 0;
}
编译:
g++ -g -o camtest camtest.cpp -I. `pkg-config --cflags --libs opencv`
python版本:
import cv2
import sys
cam = cv2.VideoCapture(int(sys.argv[1]))
#cam2 = cv2.VideoCapture(3)
(grabbed,frame)=cam.read()
#(grabbed2,frame2) = cam2.read()
print 'grab',grabbed
#print 'grab2',grabbed2
if grabbed:
cv2.imshow('abc', frame)
#cv2.imshow('def',frame2)
cv2.waitKey(5000)
也可以通过这种方法驱动多个摄像头,如上述Python代码中被注释的部分。