domenica 25 agosto 2013

OpenCV in C++

Per tentare in futuro di usare il riconoscimento real-time degli oggetti ho convertito lo script in Python visto in questo post in questa versione in C++

si compila, come gia' indicato, mediante

g++ `pkg-config --cflags --libs opencv` opencv.cpp -o opencv
-------------------------------------------------------------
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdlib.h>


using namespace cv;
using namespace std;


int msleep(unsigned long milisec)  
{  
    struct timespec req={0};  
    time_t sec=(int)(milisec/1000);  
    milisec=milisec-(sec*1000);  
    req.tv_sec=sec;  
    req.tv_nsec=milisec*1000000L;  
    while(nanosleep(&req,&req)==-1)  
        continue;  
    return 1;  
}

int main(int argc, char* argv[])
{
    VideoCapture cap(0); // open the video camera no. 0

    if (!cap.isOpened())  // if not success, exit program
    {
        cout << "Cannot open the video file" << endl;
        return -1;
    }

   double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
   double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video

    vector<int> compression_params;
    compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); 
    compression_params.push_back(98); /
    cout << "Frame size : " << dWidth << " x " << dHeight << endl;
    namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
    int i = 0;
   while (1)
    {
        Mat frame;
i++;
        bool bSuccess = cap.read(frame);
         if (!bSuccess) 
        {
             cout << "Cannot read a frame from video file" << endl;
             break;
        }
        stringstream ss;
ss << std::setfill('0') << std::setw(5) << i;
      bool bSuccess2 = imwrite("a_"+ss.str()+".jpg", frame, compression_params); 
msleep(1000);
    }
    return 0;
}