Fail to open camera with opencv

#1

Hi all, I am using OpenCV to open my webcam and the code is as followed:

 #include "ofApp.h"
#include "opencv2/opencv.hpp"
//--------------------------------------------------------------
void ofApp::setup() {

	ofSetFrameRate(30);
	ofBackground(0);
	ofSetWindowTitle("cam");

	this->cap.open(1);
	
	if (!this->cap.isOpened()) {
		cout << "not opened" << endl;
	}


	this->cap_size = cv::Size(1280, 720);
	ofSetFrameRate(this->cap.get(CV_CAP_PROP_FPS));

	this->image.allocate(this->cap_size.width, this->cap_size.height, OF_IMAGE_COLOR);
	this->frame = cv::Mat(this->image.getHeight(), this->image.getWidth(), CV_MAKETYPE(CV_8UC3, this->image.getPixels().getNumChannels()), this->image.getPixels().getData(), 0);

}

cv::VideoCapture cap;
I am using VideoCapture function.

The cap.isOpened() always returns false. I tried open(0), open(1), open(-1) but still failed to open my webcam.

Any suggestions?
Thanks!

#2
this->cap.open("video1.mp4");

I tried playing video. It still doesn’t work. The isOpend() function still returns false;