Ask Your Question
0

store cv::Mat data in object?

asked Aug 14 '13

MattiasR gravatar image

I have 2 questions. 1. Can I get the cv::Mat data from an image? The image is about 10x10 pixels, and grayscale. and I want to store it in a class like the array below.

2. With the data form question 1. how do I create an cv::mat object from data that is stored like:

{34, 6, 23, 67, 45 .............};

Why? I want to store the images in code, instead of having a lot of small images. Don't know if it is the best, but it fits my project really well :D

Thanks!

Preview: (hide)

2 answers

Sort by » oldest newest most voted
1

answered Aug 14 '13

updated Aug 14 '13

The simplest way, that comes to my mind is to save the information into vector like structure, and that structure is saved/readied from file.

For example:

  1. Get the size of the image (H and W)

  2. First 2 elements of the vector are the height and width.

  3. After that ,in two nested loops , get every pixel value and put it into the vector

  4. Finally, save the vector value by value, for example in csv file

Because we have the resolution of the image, we can reproduce the input image, without any difference.

Preview: (hide)
1

answered Aug 14 '13

Guanta gravatar image

updated Aug 14 '13

  1. Question: Yes, just access the data-field. e.g.

    cv::Mat1f a(2,2); float* matrix_data = (float*) a.data; // Note: static cast is probably more apropriate

Note: that the matrix_data will be de-allocated if the matrix a loses its scope, so a safer way would be to copy it (e.g. using memcpy).

  1. Question: yes you can put a matrix-header on top of your data.

    float* matrix_data = new float[1]; matrix_data = 123.0; cv::Mat1f a(1,1,matrix_data);

The same also works with std::vector.

By the way: I would always keep the data, i.e. your images, as matrices: 1. it is safer (no own memore allocations/deletions needed) and 2. it makes the code easier to read and to use.

Please also have a look at http://docs.opencv.org/modules/core/doc/basic_structures.html#mat.

Preview: (hide)

Question Tools

Stats

Asked: Aug 14 '13

Seen: 824 times

Last updated: Aug 14 '13