Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How can I create dynamic template type

Tags:

c++

I have the following piece of code, which I created for changing the intensity of a pixel in an OpenCV image (Cv::Mat class).

As you can see, I'm looping in both cases, but with different template type.

The 'transfer' function can be overloaded.

My question is, therefore, how can I create dynamic template type so that it looks better ..

Mat mat = _mat.clone() ;
int channels = mat.channels();

switch(channels)
{
case 1: 
    for (int i=0; i<mat.rows; i++)
    {
        for (int j=0; j<mat.cols; j++)
        {
            uchar src = mat.at<uchar>(i,j);
            uchar dst = mat.at<uchar>(i,j);

            t.transfer(src, dst);
        }
    }
    break;

case 3: 
    for (int i=0; i<mat.rows; i++)
    {
        for (int j=0; j<mat.cols; j++)
        {
            Vec3b src = mat.at<Vec3b>(i,j);
            Vec3b dst = mat.at<Vec3b>(i,j);

            t.transfer(src, dst);
        }
    }
    break;
}

return mat ;
like image 294
Dror Weiss Avatar asked Apr 13 '12 19:04

Dror Weiss


1 Answers

How about something like this:

template <typename U, typename T>
void transfer_mat(Mat & mat, T & t)
{
    for (int i = 0, r = mat.rows; i != r; ++j)
    {
        for (int j = 0, c = mat.cols; j != c; ++j)
        {
            U src = mat.at<U>(i, j);
            U dst = mat.at<U>(i, j);

            t.transfer(src, dst);
        }
    }
}

Then you can say:

switch(channels)
{
case 1:
    transfer_mat<uchar>(mat, t);
    break;
case 2:
    transfer_mat<Vec3b>(mat, t);
    break;
}
like image 63
Kerrek SB Avatar answered Sep 27 '22 18:09

Kerrek SB