2012-09-30 98 views
0

好吧,所以我試圖讓用戶輸入列數和行數,然後讓輸出帶出一個隨機數矩陣,然後是一個平滑的圖像矩陣,找到每個像素的平均濾波器陣列。現在我已經到了它可以給我一個隨機數矩陣的地方,但平滑後的矩陣完全沒有問題。現在我寫的代碼只關注具有4個鄰居的整數,但顯然我做了錯誤的事情。圖像平滑在c

#include <stdio.h> 
#include <stdlib.h> 
#include <conio.h> 
#include <time.h> 
// function that randomly generates numbers 
void fillArray(int a[10][20], int m, int n) 
{ 
    int random; 
    int i,j; 
     for (i=0;i<m;i++) 
     { 
      for (j=0;j<n;j++) 
      { 
          random=rand()%100; 
          a[i][j]=random; 
          } 
          } 
    } 
    // function that prints the first matrix of random numbers 
    void printarray (int a[10][20], int m, int n) 
{ 
int i,j; 
for (i=0;i<m;i++) 
{ 
    for (j=0;j<n;j++) 
     { 
        printf("%4d", a[i][j]); 
        } 
        printf("\n"); 
        } 
    } 
    // function that finds the mean for any number and its 4 nieghbors 
    void smooth (int a[10][20], int m, int n) 
{ 

int i,j; 
for (i=1;i<m;i++) 
{ 
    for (j=1;j<n;j++) 
    { 
     a[i][j]=a[i][j]=(a[i-1][j]+a[i][j-1]+a[i+1][j]+a[i][j+1])/4; 
     printf("%4d",a[i][j]); 
     } 
     printf("\n"); 
} 
} 
int main() 
{ 

int a[10][20]; 
int m,n; 
srand(time(NULL)); 
//User input 
printf("please enter number of columns and rows"); 
scanf("%d %d", &m,&n); 
fillArray(a,m,n); 
printarray (a,m,n); 
printf("The smoothed image is\n"); 
smooth(a,m,n); 
getch(); 
return 0; 
} 

現在如果我進入3和3我會得到這樣的事情:

23 43 54 
12 76 89 
56 98 24 

The smoothed image is 
347373849493234343 
12 23345345345 
2132334565645645645 

任何人有什麼想法?

+0

我感到驚訝的是,當你平滑角落和邊緣時,你的程序沒有遇到錯誤;這些應該是特殊的casses,對待不同。 –

+0

@coraldoe,我已經修復了大部分程序,現在我唯一的問題是我似乎無法修復右邊界和右邊兩個邊界的邊界問題。 – DatDudeJC

回答

0

它看起來像你訪問一個[m] [..]和一個[..] [n](因爲你循環,而我例如< m,並訪問i + 1)數字生成功能。

編輯:當分配值,每個迴路從0到m-1/n-1個

for (i=0;i<m;i++) 
     { 
      for (j=0;j<n;j++) 
      { 
          random=rand()%100; 
          a[i][j]=random; 
          } 
          } 

然而當使用這些值時,每個循環從1到m-1 /正1,但這種循環內使用的相鄰小區(I-1,J-1,I + 1,J + 1)

for (i=1;i<m;i++) 
{ 
    for (j=1;j<n;j++) 
    { 
     a[i][j]=(a[i-1][j]+a[i][j-1]+a[i+1][j]+a[i][j+1])/4; 
     } 
} 
} 

這意味着,在最後迭代(I = M - 1),您訪問未初始化的單元格,因爲您訪問i + 1 = m 請記住,多維數組實際上是內存中的一維數組,所以一些這些電話是不是真的未初始化的值,但也有一些

解決這個問題,你可以循環,直到M/N在分配階段(而不是M-1/N-1)

+0

我不確定我是否完全理解你的意思,你能指出你的意思嗎? – DatDudeJC

+0

看到我的編輯,希望它現在更清晰 –

+0

好吧,我的程序大部分都在工作,但我可能已經有點奇怪了。我現在可以返回左上角的數字,數字的左側和中間數字的值,但我只能單獨執行它們。有沒有辦法將3組合併成一個矩陣(最終我需要將9組合)或者我是否完全錯誤? – DatDudeJC