2014-04-01 48 views
0

我正在對像素進行一些平均,我知道這個循環可以用於任何二維數組。但如果src是一個Mat圖像(OpenCV),這怎麼能工作呢? 我有這麼多的困難通過這些參數在墊圖像功能 我的問題是否有意義?如果輸入(src)是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 ; 
     } 
    } 
} 

回答

1

我認爲你只是想知道如何爲你的二維數組做訪問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是類似於你在二維數組。

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);