如果输入(src)是Mat图像,这个循环如何工作?

时间:2014-04-01 22:50:23

标签: opencv

我正在研究像素的平均值,我知道这个循环可以用于任何2d数组。但是如果src是Mat图像(OpenCV),它怎么能工作呢? 我在Mat函数的函数中传递这些参数有很多困难 我的问题有意义吗?

#include <iostream>

const unsigned dim = 3;
typedef int array_type [dim][dim];

这是循环:

void average(array_type& dest, const array_type& src)
{
    // corners:
    dest[  0  ][  0  ] = 
        (src[  0  ][  0  ] + src[  0  ][  1  ] + src[  1  ][  0  ] + src[  1  ][  1  ])/4;
    dest[dim-1][  0  ] = 
        (src[dim-1][  0  ] + src[dim-2][  0  ] + src[dim-1][  1  ] + src[dim-2][  1  ])/4;
    dest[  0  ][dim-1] = 
        (src[  0  ][dim-1] + src[  1  ][dim-1] + src[  0  ][dim-2] + src[  1  ][dim-2])/4;
    dest[dim-1][dim-1] = 
        (src[dim-1][dim-1] + src[dim-2][dim-1] + src[dim-1][dim-2] + src[dim-2][dim-2])/4;

    // top, bottom, and sides:
    for (unsigned i = 1; i < dim - 1; ++i)
    {
        const unsigned j = dim - 1;

        dest[0][i] = 
            (src[0][i-1] + src[0][i] + src[0][i+1] + src[ 1 ][i-1] + src[ 1 ][i] + src[ 1 ][i+1])/6;
        dest[j][i] = 
            (src[j][i-1] + src[j][i] + src[j][i+1] + src[j-1][i-1] + src[j-1][i] + src[j-1][i+1])/6;

        dest[i][0] = 
            (src[i-1][0] + src[i][0] + src[i+1][0] + src[i-1][ 1 ] + src[i][ 1 ] + src[i+1][ 1 ])/6;
        dest[i][j] = 
            (src[i-1][j] + src[i][j] + src[i+1][j] + src[i-1][j-1] + src[i][j-1] + src[i+1][j-1])/6;
    }

    // middle:
    for (unsigned i = 1; i < dim - 1; ++i)
    {
        for (unsigned j = 1; j < dim - 1; ++j)
        {
            dest[i][j] = (src[i-1][j-1] + src[i-1][j] + src[i-1][j+1] +
                          src[ i ][j-1] + src[ i ][j] + src[ i ][j+1] +
                          src[i+1][j-1] + src[i+1][j] + src[i+1][j+1]) / 9 ;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我认为你只是想知道如何像在2D数组中那样访问Mat image像素。请参阅以下代码:

for(int i=0; i<image.rows; i++)
{
    for(int j=0; j<image.cols; j++)
    {
        value_from_Mat_array = image.at<uchar>(i,j);
    }
}

因此,i,j是与2D数组相似的索引。

答案 1 :(得分:1)

你可能根本不会使用opencv进行循环,而是使用filter2D()代替:

Mat img; // your original image
Mat res; // filtered
Mat kernel(3,3,CV_32F,Scalar(1.0f/9));
filter2D(img,res,-1,kernel);