Ask Your Question

Revision history [back]

Snapshot using command line.

Hi Folks.

I am trying to take a snapshot from a usb camera from the command line. I have it kind of working. I want to have 3 different commands: open, snapshot and close. I want to open the camera initially and then take snapshots as I please. However the frame grab seems to close the camera down and so it has to be opened again. Is it possible to use one command to open the camera and then another to grab the frame and another to close the camera and is it possible to grab a frame and leave the camera open? My code is below,

Thanks,

Mark.

include <opencv2 opencv.hpp="">

include <iostream>

using namespace cv; using namespace std;

std::string open_cmd("open"); std::string close_cmd("close"); std::string snapshot_cmd("snap");

int main(int argc, char argv[], char*) { //Open the first webcam plugged in the computer

cv::VideoCapture camera(2);
if (!camera.isOpened())
{
    std::cerr << "ERROR: Could not open camera" << std::endl;
    //return 1;
}


int count;

printf("This program was called with \"%s\".\n", argv[0]);

if (argc > 1)
{
    for (count = 1; count < argc; count++)
    {
        printf("argv[%d] = %s\n", count, argv[count]);
    }
}
else
{
    printf("The command had no other arguments.\n");
}

// return 0;

//Create a window to display the images from the webcam
cv::namedWindow("Webcam", CV_WINDOW_AUTOSIZE);

vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);


//Pick up a new frame and display it until you press a key
while (1)
{
    //This will contain the image from the webcam
    cv::Mat frame;

    //Capture the next frame from the webcam
    camera >> frame;

    //Show the image on the window
    cv::imshow("Webcam", frame);

    std::string input_cmd(argv[1]);

    if (open_cmd.compare(input_cmd) == 0) {
        cv::VideoCapture camera(2);
        cv::imshow("Webcam", frame);
        //return 0;
    }
    else if (snapshot_cmd.compare(input_cmd) == 0) {
        camera >> frame;
        imwrite("MyImage.png", frame, compression_params);
        return 0;
    }
    else if (close_cmd.compare(input_cmd) == 0) {
        camera.release();
        //return 0;
    }


}

//Success. The program accomplished its mission and now it can go
// to the heaven of programs.
return 0;

}