OpenCV Lab

Introduction

OpenCV is a library of programming functions mainly aimed at real-time computer vision. This one of most widely used computer vision lib.

Main Modules:

Module
Core
imgproc
imgcodecs
videoio
highgui
video
calib3d
features2d
objdetect
dnn
ml
flann
photo
stitching
gapi

Core

Mat Data type

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 storing).

cv::Mat img = cv::imread("test.png", cv::IMREAD_COLOR)
cv::Mat new_img = img;

The assign operator only copies the matrix header.

APIS:

cv::Mat::clone() - Creates a full copy of the array and the underlying data.

cv::Mat::copyTo - Copies the matrix to another one.

The major difference between these two API's is that, When the destination matrix and the source matrix have the same type and size, copyTo will not change the address of the destination matrix, while clone will always allocate a new address for the destination matrix.

cv::Mat img = cv::imread("test.png", cv::IMREAD_COLOR)
cv::Mat new_img = img.clone();

Color Space

RGB is the most common as our eyes use something similar, however keep in mind that OpenCV standard display system composes colors using the BGR color space (red and blue channels are swapped places).

Measure a operation time

double time = (double)cv::getTickCount();
//do something
time = ((double)cv::getTickCount() - time)/cv::getTickFrequency();
std::cout << "Time: " << time << std::endl;

Image matrix stored in Memory

Gray Scale

image info

BGR

image info

Intersting one 😃

If the memory allcoated for Matrix is Continuous then there is a efficent way to access them.

Mat& ScanImageAndReduceC(Mat& img, const uchar* const table)
{
    // accept only char type matrices
    CV_Assert(img.depth() == CV_8U);
    int channels = img.channels();
    int nRows = img.rows;
    int nCols = img.cols * channels;
    if (img.isContinuous())
    {
        nCols *= nRows;
        nRows = 1;
    }
    int i,j;
    for( i = 0; i < nRows; ++i)
    {
        for ( j = 0; j < nCols; ++j)
        {
            //do something
        }
    }
    return I;
}