Wednesday 10 February 2016

Zeros,Ones and Eyes in OpenCV


Matlab style Initializers
Mat::zeroes
Each element of the matrix is zero of the specified size.
Mat A;
A = Mat::zeros(3, 3, CV_32F);


Mat::ones
Each element of the matrix is one of the specified size
Mat A;
A = Mat::ones(3, 3, CV_32F);


Mat::eyes
It returns an identity matrix of the specified size.
Mat A;
A = Mat::eyes(3, 3, CV_32F);


Note:
We can also mention the scale factor of the matrix.
e.g:
A = Mat::ones(3, 3, CV_32F)* 5;
Here each element of the matrix is 5, because each element of the uniy matrix is multiplied by 5.


#include <opencv2/core/core.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp> 
 
using namespace cv;
using namespace std;
 
int main()
{
    Mat imgA = Mat::eye(5, 5, CV_8UC1);
cout << "imgA = \n " << imgA << "\n\n";
 
Mat imgB = Mat::ones(4, 4, CV_8UC1);
cout << "imgB = \n " << imgB << "\n\n";
 
Mat imgC = Mat::zeros(3,3, CV_8UC1);
cout << "imgC = \n " << imgC << "\n\n";
 
return 0;
}

Output:



Note:
Here we have selected the single channel matrix.(CV_8UC1)
For 3 channel matrices:


Code:
#include <opencv2/core/core.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp> 
 
using namespace cv;
using namespace std;
 
int main()
{
    Mat imgA = Mat::eye(5, 5, CV_8UC3);
cout << "imgA = \n " << imgA << "\n\n";
 
Mat imgB = Mat::ones(4, 4, CV_8UC3);
cout << "imgB = \n " << imgB << "\n\n";
 
Mat imgC = Mat::zeros(3,3, CV_8UC3);
cout << "imgC = \n " << imgC << "\n\n";
 
return 0;
}





See the difference in the output.Here the zeros,ones and eyes operator is applied only to 1 channel of the matrix.Rest of the other channel elements are taken 0.Thus two columns of 0 can be seen in between.

Also we doesn't mention the no. of channels by default it takes 1.
ie. CV_8U is equivalent to CV_8UC1.

No comments:

Post a Comment