0908
0908

Reputation: 31

Array to OpenCV matrix

I have a array double dc[][] and want to convert this as to a IplImage* image and further to a video frame. What I had to do was I was given a video and I extracted out some features and then make a new video of the extracted features. My approach was I divided the video into frames extracted the features from each frame then did the updation like this and in each iteration of frame I get a new dc

double dc[48][44];
for(int i=0;i<48;i++)
{
  for(int j=0;j<44;j++)
  {
     dc[i][j]=max1[i][j]/(1+max2[i][j]);
  }
}

Now I need to save this dc in such a way that I can reconstruct the video.Anybody help me with this. Thanks in advance

Upvotes: 0

Views: 889

Answers (1)

alrikai
alrikai

Reputation: 4194

If you're okay with using Mat, then you can make a Mat for existing user-allocated memory. One of the Mat constructors has the signature:

Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)

where the parameters are:

rows: the memory height, 
cols: the width, 
type: one of the OpenCV data types (e.g. CV_8UC3), 
data: pointer to your data, 
step: (optional) stride of your data

I'd encourage you to take a look at the documentation for Mat here

EDIT: Just to make things more concrete, here's an example of making a Mat from some user-allocated data

int main()
{
    //allocate and initialize your user-allocated memory
    const int nrows = 10;
    const int ncols = 10;
    double data[nrows][ncols];
    int vals = 0;
    for (int i = 0; i < nrows; i++)
    {
        for (int j = 0; j < ncols; j++)
        {
            data[i][j] = vals++;
        }
    }
    //make the Mat from the data (with default stride)
    cv::Mat cv_data(nrows, ncols, CV_64FC1, data);
    //print the Mat to see for yourself
    std::cout << cv_data << std::endl;
} 

You can save a Mat to a video file via the OpenCV VideoWriter class. You just need to create a VideoWriter, open a video file, and write your frames (as Mat). You can see an example of using VideoWriter here

Here's a short example of using the VideoWriter class:

//fill-in a name for your video 
const std::string filename = "...";
const double FPS = 30;
VideoWriter outputVideo;
//opens the output video file using an MPEG-1 codec, 30 frames per second, of size height x width and in color 
outputVideo.open(filename, CV_FOURCC('P','I','M,'1'), FPS, Size(height, width));

Mat frame;
//do things with the frame
// ...

//writes the frame out to the video file
outputVideo.write(frame);

The tricky part of the VideoWriter is the opening of the file, as you have a lot of options. You can see the names for different codecs here

Upvotes: 1

Related Questions