I've been working with camera videos using OpenCV recently. On Linux, installing OpenCV can be quite cumbersome because it needs to be manually compiled. However, Homebrew makes everything easy on Mac OS.

Installation

brew install opencv

Then we set env variable. Add the following line to ~/.bashrc or ~/.zshrc. Since the OpenCV version and the Homebrew installation path may differ, ensure that the path is correct.

# opencv4
export PATH=/opt/homebrew/opt/opencv@4/bin:$PATH
export PKG_CONFIG_PATH=/opt/homebrew/Cellar/opencv/4.8.1_5/lib/pkgconfig:$PKG_CONFIG_PATH
export DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:/opt/homebrew/Cellar/opencv/4.8.1_5/lib

Then compile and run the following code. It will access the camera and capture frames. Press any key to exit the program.

#include <opencv2/opencv.hpp>
#include <iostream>

int main(int argc, char *argv[])
{
    cv::VideoCapture capture(0);
    if (!capture.isOpened())
    {
        std::cerr << "ERROR: camera failed to open.\n";
        return 1;
    }
    cv::Mat frame;
    while (true)
    {
        capture >> frame;
        if (frame.empty())  { break; }
        cv::imshow("Camera View", frame);
        if (cv::waitKey(1) >= 0)    { break; }
    }

    capture.release();
    cv::destroyAllWindows();
    return 0;
}

Remember to specify the paths to the header files and libraries when compiling.

g++ run.cpp -o output `pkg-config --cflags --libs opencv4`