官术网_书友最值得收藏!

  • Mastering OpenCV 4
  • Roy Shilkrot David Millán Escrivá
  • 342字
  • 2021-07-02 14:47:34

Accessing the webcam

To access a computer's webcam or camera device, you can simply call the open() function on a cv::VideoCapture object (OpenCV's method of accessing your camera device), and pass 0 as the default camera ID number. Some computers have multiple cameras attached, or they do not work with a default camera of 0, so it is common practice to allow the user to pass the desired camera number as a command-line argument, in case they want to try camera 1, 2, or -1, for example. We will also try to set the camera resolution to 640 x 480 using cv::VideoCapture::set() to run faster on high-resolution cameras.

Depending on your camera model, driver, or system, OpenCV might not change the properties of your camera. It is not important for this project, so don't worry if it does not work with your webcam.

You can put this code in the main() function of your main.cpp file:

auto cameraNumber = 0; 
if (argc> 1)
cameraNumber = atoi(argv[1]);

// Get access to the camera.
cv::VideoCapture camera;
camera.open(cameraNumber);
if (!camera.isOpened()) {
std::cerr<<"ERROR: Could not access the camera or video!"<< std::endl;
exit(1);
}

// Try to set the camera resolution.
camera.set(cv::CV_CAP_PROP_FRAME_WIDTH, 640);
camera.set(cv::CV_CAP_PROP_FRAME_HEIGHT, 480);

After the webcam has been initialized, you can grab the current camera image as a cv::Mat object (OpenCV's image container). You can grab each camera frame by using the C++ streaming operator from your cv::VideoCapture object in a cv::Mat object, just like if you were getting input from a console.

OpenCV makes it very easy to capture frames from a video file (such as an AVI or MP4 file) or network stream instead of a webcam. Instead of passing an integer such as  camera.open(0), pass a string such as camera.open("my_video.avi") and then grab frames just like it was a webcam. The source code provided with this book has an initCamera() function that opens a webcam, video file, or network stream.
主站蜘蛛池模板: 迁西县| 达孜县| 乳山市| 甘孜县| 衡东县| 汶川县| 斗六市| 五家渠市| 开封市| 博白县| 肇庆市| 平顶山市| 荥阳市| 阿合奇县| 合阳县| 简阳市| 平南县| 昌吉市| 石泉县| 平舆县| 白城市| 西盟| 南江县| 东宁县| 崇阳县| 南丰县| 皮山县| 洪湖市| 石屏县| 香港| 蒲城县| 怀安县| 阳原县| 芷江| 澜沧| 鄂尔多斯市| 郑州市| 永吉县| 阜宁县| 东阿县| 威海市|