openFrameworksでWebカメラを自動的に接続する

oFで自動的に接続するシリーズ。

ofVideoGrabberで適当にデバイスの数字とかでやってるとノートPC内蔵のWebカメラ起動しちゃったりするんだけど、それを避けて常に特定のカメラを開けるようにする。避け方は簡単でWebカメラの名前(=ofVideoDeviceのdeviceName)を見て開けばOK。今回はロジクールのC920ってカメラだからC920って名前があるやつを開くだけ。

#define CAM_WIDTH 1296
#define CAM_HEIGHT 729

ofVideoGrabber cam;

void HogeClass::setup(){
    if(cam.isInitialized() == false){
        cout << "Initalizing cam" << endl;
        int index = 0;
        vector<ofVideoDevice> devices = cam.listDevices();
        for(int i=0; i<devices.size(); i++){
            ofVideoDevice& device = devices.at(i);
            cout << i  << ":" << device.deviceName << ":" << endl;
            if(device.deviceName.find("C920") != std::string::npos){
                index = i;
            }
        }
        cam.setDeviceID(index);
        cam.initGrabber(CAM_WIDTH, CAM_HEIGHT);
        cout << cam.getWidth() << "," << cam.getHeight() << endl;
        
        return;
    }
}

CAM_WIDTHとCAM_HEIGHTの数字はC920における秘伝のタレ。良いカメラでっせ。

Logicool ロジクール HD プロ ウェブカム c920r

Logicool ロジクール HD プロ ウェブカム c920r

2018/05/16 コード修正

@shigeodayo氏に指摘されてdevice.deviceName.find()のところの判定をちゃんとstd::string::nposにするように変更。また、cam.listDevices()がループ内で呼び出されてコンソールに意図しない出力が出てるのも修正。