2013-05-05 57 views
0

我剛剛開始在Opencv編程,我試圖實現一個簡單的平均過濾器。我知道在OpenCv中有一個內置的函數,但我不想使用它,但我期待了解空間域過濾機制及其與卷積的相似性。下面是一個功能我已經寫在輸入和輸出灰度平均過濾器Opencv

void averageFilter(Mat& Input,Mat& Output) 
{ 
    int row=Input.rows; 
    int col=Input.cols; 
    //uchar *input_data=Input.data; 
    //uchar *output_data=Output.data; 
    int size=1; 
    uchar count=0; 
    uchar sum=0; 

    //int nChannels=1; 

    for(int j = 1 ; j < Input.rows-1; ++j) 
    { 
     const uchar* previous = Input.ptr<uchar>(j - 1); 
     const uchar* current = Input.ptr<uchar>(j ); 
     const uchar* next  = Input.ptr<uchar>(j + 1); 

     uchar* output = Output.ptr<uchar>(j); 

     for(int i= 1;i < (Output.cols-1); ++i) 
     { 
      *output++ = (current[i] 
         +current[i-1] + current[i+1] + previous[i] +next[i]+previous[i-1]+previous[i+1]+next[i-1]+next[i+1])/9; 
     } 
    } 
} 

這不進行平均是需要,請你告訴我,我做錯了什麼?

謝謝

回答

1

您通過與unsigned char盡一切可能獲得的溢出,所以嘗試這樣的事情

for(int i= 1;i < (Output.cols-1); ++i) 
{ 
    double dResult = (current[i] +current[i-1] + current[i+1] + 
         previous[i] +next[i]+previous[i-1]+previous[i+1]+ 
         next[i-1]+next[i+1])/9.0; 
    *output++ = (unsigned char)dResult; 
} 

另外,我覺得你的previousnext行的像素是錯誤的 - 你需要按寬度對行號進行拼寫。與output類似。

編輯更正,我剛剛檢查了OpenCV文檔和ptr是一個行指針,所以忽略我的最後一條評論!

+0

我想我明白你的意思,我會嘗試更改謝謝 – Whereismywall 2013-05-05 08:40:59