OpenCV Tutorial: Creating Mat Objects (2024)

Creating Mat Objects

OpenCV Tutorial: Creating Mat Objects (1)

OpenCV Tutorial: Creating Mat Objects (2)



bogotobogo.com site search:

Creating Mat objects


Constructor Mat()

We'll learn how we can write a matrix to an image file, however, for debugging purposes it's much more convenient to see the actual values. We do this using the << operator of Mat.

Here is a testing file, t.cpp:

#include <opencv2/core/core.hpp>#include <iostream>using namespace cv;using namespace std;int main( int argc, char** argv ){ Mat img(2,2, CV_8UC3, Scalar(126,0,255)); cout << "img = \n " << img << "\n\n"; return 0;}

and with the cmake file :

cmake_minimum_required(VERSION 2.8)project( Tutorials )find_package( OpenCV REQUIRED )add_executable( Tutorials t.cpp )target_link_libraries( Tutorials ${OpenCV_LIBS} )

So, put the two files in a directory called Tutorials and run cmake:

$ cmake .-- Configuring done-- Generating done-- Build files have been written to: /home/khong/OpenCV/workspace/Tutorials$ makeScanning dependencies of target Tutorials[100%] Building CXX object CMakeFiles/Tutorials.dir/t.cpp.oLinking CXX executable Tutorials[100%] Built target Tutorials

If we run the code:

$ ./Tutorials img = [126, 0, 255, 126, 0, 255; 126, 0, 255, 126, 0, 255]

If we modify the row from 2 to 5:

Mat img(2,2, CV_8UC3, Scalar(126,0,255));==>Mat img(5,2, CV_8UC3, Scalar(126,0,255));

We get:

img = [126, 0, 255, 126, 0, 255; 126, 0, 255, 126, 0, 255; 126, 0, 255, 126, 0, 255; 126, 0, 255, 126, 0, 255; 126, 0, 255, 126, 0, 255]

Here is the convention for the data type used in CV_8UC3:

CV_[The number of bits per item][Signed or Unsigned][Type Prefix]C[The channel number]

So, here is the meaning of the CV_8UC3:
we want to use unsigned char types('U') that are 8 bit long and each pixel has 3 of these to form the 3 channels. The Scalar is four element short vector.

Channels

Single channel array

OpenCV Tutorial: Creating Mat Objects (3)

Here is a single channel array with 8 bit unsigned integers. As the datatype of this array is 8 bit unsigned integers, each element should have a value from 0 to 255.

  1. CV_8U (8 bit unsigned integer)
  2. CV_8S (8 bit signed integer)
  3. CV_16U (16 bit unsigned integer)
  4. CV_16S (16 bit signed integer)
  5. CV_32S (32 bit signed integer)
  6. CV_32F (32 bit floating point number)
  7. CV_64F (64 bit float floating point number)

Multi channel array

OpenCV Tutorial: Creating Mat Objects (4)

Here is a single channel array with 8 bit unsigned integers. As the datatype of this array is 8 bit unsigned integers, each element should have a value from 0 to 255.

  1. CV_8UC1 (single channel array with 8 bit unsigned integers)
  2. CV_8UC2 (2 channel array with 8 bit unsigned integers)
  3. CV_8UC3 (3 channel array with 8 bit unsigned integers)
  4. CV_8UC4 (4 channel array with 8 bit unsigned integers)
  5. CV_8UC(n) (n channel array with 8 bit unsigned integers (n can be from 1 to 512) )

Note: CV_8U = CV_8UC1 = CV_8UC(1)


Here are the samples of the convention:

  1. Mat img(2, 4, CV_32F ); // 2x4 single-channel array with 32 bit floating point numbers
  2. Mat img(3, 5, CV_8FC(4) ); // 3x5 4-channel array with 8 bit floating point numbers
  3. Mat img(Size(480, 360), CV_64UC3 ); //480x360 3-channel array with 64 bit unsigned integers

Multi-dimensional Mat Object

We can create a matrix with more than two dimensions. We can use array to initialize the constructor:

int arr[3] = {4,3,2};Mat L(3, arr, CV_8UC(1), Scalar::all(0));

We specified its dimension of 3, then pass a pointer containing the size for each dimension.

Creating a header

We can create a header for an already existing IplImage pointer:

IplImage* img = cvLoadImage("sample.png", 1);Mat mtx(img); 

Mat mtx(img) makes IplImage pointer img to point Mat.

create()

Let's run the follow code:

#include <opencv2/core/core.hpp>#include <iostream>using namespace cv;using namespace std;int main( int argc, char** argv ){ Mat img(5,4, CV_8UC3, Scalar(0,0,255)); cout << "img = \n"<< " " << img << "\n\n"; img.create(5,4, CV_8UC(3)); cout << "img = \n"<< " " << img << "\n\n"; return 0;}

The output is:

img = [ 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255]img = [ 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255]

No problem here. However, if we run after modifying the size:

#include <opencv2/core/core.hpp>#include <iostream>using namespace cv;using namespace std;int main( int argc, char** argv ){ Mat img(5,4, CV_8UC3, Scalar(0,0,255)); cout << "img = \n"<< " " << img << "\n\n"; img.create(3,2, CV_8UC(3)); cout << "img = \n"<< " " << img << "\n\n"; return 0;}

The new output after changing the size:

img = [ 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255; 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255]img = [ 50, 53, 53, 0, 0, 0; 0, 0, 0, 0, 0, 0; 0, 0, 0, 0, 0, 0]

As we can see from the above example, we cannot initialize the matrix values with this constructor. It will only reallocate its matrix data memory if the new size will not fit into the old one.

zeros(), ones(), eye()

Let's look at other types of initializer which are MATLAB style:

Mat imgA = Mat::eye(4, 4, CV_64F);cout << "imgA = \n " << imgA << "\n\n";Mat imgB = Mat::ones(2, 2, CV_32F);cout << "imgB = \n " << imgB << "\n\n";Mat imgC = Mat::zeros(3,3, CV_8UC1);cout << "imgC = \n " << imgC << "\n\n";

Output:

imgA = [1, 0, 0, 0; 0, 1, 0, 0; 0, 0, 1, 0; 0, 0, 0, 1]imgB = [1, 1; 1, 1]imgC = [ 0, 0, 0; 0, 0, 0; 0, 0, 0]

comma separated initializers

We can also use comma separated initializers:

#include <opencv2/core/core.hpp>#include <iostream>using namespace cv;using namespace std;int main( int argc, char** argv ){ Mat img = (Mat_<int>(3,3) << 1, 0, 1, 0, -2, 0, 3, 0, 3); cout << "img = \n " << img << "\n\n"; return 0;}

Output:

img = [1, 0, 1; 0, -2, 0; 3, 0, 3]

clone()

Here is an example of using clone():

#include <opencv2/core/core.hpp>#include <iostream>using namespace cv;using namespace std;int main( int argc, char** argv ){ Mat img = (Mat_<int>(3,3) << 1, 0, 1, 0, -2, 0, 3, 0, 3); cout << "img = \n " << img << "\n\n"; Mat row_cloned_img = img.row(1).clone(); cout << "row_cloned_img = \n " << row_cloned_img << "\n\n"; return 0;}

Output:

img = [1, 0, 1; 0, -2, 0; 3, 0, 3]row_cloned_img = [0, -2, 0]
OpenCV Tutorial: Creating Mat Objects (2024)

FAQs

What is the mat object in OpenCV? ›

Mat is basically a class with two data parts: the matrix header (containing information such as the size of the matrix, the method used for storing, at which address is the matrix stored, and so on) and a pointer to the matrix containing the pixel values (taking any dimensionality depending on the method chosen for ...

What is step in OpenCV mat? ›

step – Number of bytes each matrix row occupies. The value includes the padding bytes at the end of each row, if any.

How does OpenCV represent images? ›

In OpenCV, images are represented as 3-dimensional Numpy arrays. An image consists of rows of pixels, and each pixel is represented by an array of values representing its color. Where [72 99 143] , etc., are the blue, green, and red (BGR) values of that one pixel.

How to create a matrix in OpenCV Python? ›

Steps
  1. Import the required libraries OpenCV and NumPy. Make sure you have already installed them.
  2. Read the input image using cv2. imread() method. ...
  3. Define a transformation matrix m of size (3,3). ...
  4. Find the matrix transform of the image using cv2. ...
  5. Display the transformed image.
Dec 5, 2022

What is the difference between OpenCV Mat and Matx? ›

Short answer: cv::Mat uses the heap to store its data, while cv::Matx uses the stack. A cv::Mat uses dynamic memory allocation (on the heap). This is appropriate for big matrices (like images) and lets you do things like shallow copies of a matrix, which is the default behavior of cv::Mat.

What is the OpenCV library for mat? ›

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.

How does OpenCV Imread work? ›

imread() [1/2] Loads an image from a file. The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

What is the parameter of mat function in OpenCV? ›

Working of Mat() Function in OpenCV

The Mat function takes four parameters namely rows, columns, data type and scalar. The rows parameter passed to the Mat function represents the rows in a matrix.

What objects can OpenCV detect? ›

OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today's systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human.

What does the CV in OpenCV stand for? ›

OpenCV stands for Open Source Computer Vision library. It is an open-source library that was started by Gary Bradsky at Intel in 1999, and the first came out in 2000. After that, supported by Willow Garage then itseez.

How to make a 3x3 matrix in Python? ›

To write a 3×3 matrix in Python, one can create a nested list that has three nested lists, each with three elements. Another method is through the ndarray object. One will have to pass the 3, 3 as the number of rows and columns respectively in the parameters of the method.

How is an image converted into a matrix? ›

... the image is converted into a matrix where each pixel is stored as numbers representing the RGB values (ranging from 0 to 255 as red, blue, green concentration levels. Figure 3 illustrates an example of an image to matrix conversion.

What does mat do in Python? ›

The mat() function returns data interpreted as a matrix.

What is the OpenCV module used for? ›

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products.

What does mat mean in Java? ›

Eclipse Memory Analyzer Tool (MAT) is by far the best tool to analyze Java Heap Dumps.

References

Top Articles
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6502

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.