2016-04-26 142 views
0

所以我有一個程序試圖將一個簡單的3x3卷積矩陣應用於圖像。Opencv卷積矩陣給出了不尋常的結果

這是正在做工作中的作用:

Mat process(Mat image) { 

    int x = 2; 
    int y = 2; 
    Mat nimage(image); //just a new mat to put the resulting image on 

    while (y < image.rows-2) { 

     while (x < image.cols-2) { 

      nimage.at<uchar>(y,x) = //apply matrix to pixel 
      image.at<char>(y-1,x-1)*matrix[0]+ 
      image.at<char>(y-1,x)*matrix[1]+ 
      image.at<char>(y-1,x+1)*matrix[2]+ 
      image.at<char>(y,x-1)*matrix[3]+ 
      image.at<char>(y,x)*matrix[4]+ 
      image.at<char>(y,x+1)*matrix[5]+ 
      image.at<char>(y+1,x-1)*matrix[6]+ 
      image.at<char>(y+1,x)*matrix[7]+ 
      image.at<char>(y+1,x+1)*matrix[8]; 

      //if (total < 0) total = 0; 
      //if (total > 255) total = 255; 

      //cout << (int)total << ": " << x << "," << y << endl; 

      x++; 
     } 

     x = 0; 
     y++; 
    } 

    cout << "done" << endl; 

    return nimage; 

} 

和矩陣看起來像這樣

double ar[9] = {-1,0,0, 
       0,2,0, 
       0,0,0}; 

,這是用作輸入的圖像看起來是這樣的:

期望的輸出(我跑了相同的矩陣上在GIMP輸入圖像):

,其結果是...奇怪:

我認爲這與當我設置一個我使用的數據類型做新圖像的像素(nimage.at<uchar>(y,x) = ...),因爲無論何時我改變它,我都會得到一個不同但仍然不正確的結果。

+0

你爲什麼不使用標準的卷積fonctions提供的OpenCV? – tfv

回答

0

大約從Mat拷貝構造,重點煤礦OpenCV的文檔:

- Array用於(作爲一個整體或部分地)被分配給所構建的基質。沒有數據被這些構造函數複製。相反,指向m數據或其子數組的頭部被構造並且與其關聯。參考計數器(如果有)遞增。 因此,當您修改使用這種構造函數形成的矩陣時,您還修改了m的相應元素。如果您想擁有子陣列的獨立副本,請使用Mat::clone()

所以

Mat nimage(image); //just a new mat to put the resulting image on 

實際上並沒有創建一個新的矩陣;它會創建一個新的Mat對象,但該對象仍指向相同的矩陣。從此nimage.at(y,x)就像image.at(y,x)一樣。

要複製的圖像,使用

Mat nimage(image.clone()); //just a new mat to put the resulting image on 
+0

謝謝。您。所以。許多。我甚至沒有想過要看那部分。我將盡力在未來更詳細地查看文檔:/ – user3369663