Accessing webcam in Xcode with OpenCV (C++)

2020-02-01 07:57发布

问题:

I am trying to open the webcam and display a short capture with OpenCV. I am currently working on Xcode, with C++ language.

The code is pretty simple:

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

using namespace std;
using namespace cv;

int main(int argc, const char * argv[]) {

    // variable initialization
    Mat frame;
    VideoCapture cap;            // 0 is the webcam

    // try to open camera
    cap.open(0);
    if (!cap.isOpened()) return -1;  // check if there is no video or no way to display it

    // create a window and display the video capture
    namedWindow("Video Capture", CV_WINDOW_AUTOSIZE);
    for (int i=0; i<100; i++) {
        cap >> frame;
        imshow("Video Capture", frame);
        waitKey(1);
    }

    return 0;
}

As I run the code the following error is returned:

[access] This app has crashed because it attempted to access privacy-sensitive 
data without a usage description.  The app's Info.plist must contain an 
NSCameraUsageDescription key with a string value explaining to the 
user how the app uses this data.

Thus, I added an Info.plist file to the project (currently in the same directory where the main.cpp is) and added the description the compiler suggested:

Key: Privacy - Camera Usage Description
Value: $(PRODUCT_NAME) camera use

Then, in the project's Build Settings I referenced the file I had just written, by using the full path, as you can see in the following image:

I am sure that the path is correct, as I drag and dropped the file itself, but the compiler keeps on showing the same error and quits the execution.

回答1:

I found a solution in the end; these are the steps that I followed:

  • In Project Navigator (on the left side of Xcode IDE) right click on the project -> New File -> Property file
  • Call the file "Info.plist" and save it in the very same directory where the main.cpp is (it should work also in the upper-level dir, but this is what worked for me) as shown in the picture below:
  • Select the Info.plist file and edit it according to what explained in the question above.
  • Now we need to link the Info.plist to the project, so left click on the project in Project Navigator, select tab General and, on the left pane ("project and target list"), click on the executable under the "TARGET" section. You should be able to see a button which states "Choose Info.plist File", see the picture below:

As I noticed that the program did not start yet from the Xcode IDE directly, but I was able to navigate (in Finder) to the directory where the executable was and run the program by using the Terminal, I copy-pasted the Info.plist into that folder, as suggested here