Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create empty Mat in OpenCV?

Tags:

c++

opencv

mat

How to create empty Mat in OpenCV? After creation I want to use push_back method to push rows in Mat.

Something like:

Mat M(0,3,CV_32FC1);

or only option is:

Mat M;
M.converTo(M,CV_32FC1);

?

like image 527
mrgloom Avatar asked Jul 10 '15 09:07

mrgloom


People also ask

What is mat in OpenCV?

The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc. This class comprises of two data parts: the header and a pointer.

How do I create a blank image in C++?

To create a blank image(image filled with zeros) use cv::Mat::zeros(). It will create a matrix with the dimension and type of your choice that is filled with zeros.

What is Vec3b OpenCV?

Vec3b is the abbreviation for "vector with 3 byte entries" Here those byte entries are unsigned char values to represent values between 0 .. 255.

How is an OpenCV image stored in memory?

OpenCV has been around since 2001. In those days the library was built around a C interface and to store the image in the memory they used a C structure called IplImage. This is the one you'll see in most of the older tutorials and educational materials.


1 Answers

You can create an empty matrix simply using:

Mat m;

If you already know its type, you can do:

Mat1f m; // Empty matrix of float

If you know its size:

Mat1f m(rows, cols);  // rows, cols are int
or 
Mat1f m(size);  // size is cv::Size

And you can also add the default value:

Mat1f m(2, 3, 4.1f);
//
// 4.1 4.1 4.1
// 4.1 4.1 4.1

If you want to add values to an empty matrix with push_back, you can do as already suggested by @berak:

Mat1f m;
m.push_back(Mat1f(1, 3, 3.5f));   // The  first push back defines type and width of the matrix
m.push_back(Mat1f(1, 3, 9.1f));
m.push_back(Mat1f(1, 3, 2.7f));

// m
// 3.5 3.5 3.5
// 9.1 9.1 9.1
// 2.7 2.7 2.7 

If you need to push_back data contained in vector<>, you should take care to put values in a matrix and transpose it.

vector<float> v1 = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};
vector<float> v2 = {1.2f, 2.3f, 3.4f, 4.5f, 5.6f};

Mat1f m1(Mat1f(v1).t());
Mat1f m2(Mat1f(v2).t());

Mat1f m;
m.push_back(m1);
m.push_back(m2);

// m
// 1.1 2.2 3.3 4.4 5.5
// 1.2 2.3 3.4 4.5 5.6
like image 104
Miki Avatar answered Sep 18 '22 20:09

Miki