I’m writing a program that uses a mean filter to smooth an image. right now I’m not using an actual image, just integers and my issue is that I can get the average of the left hand corner number, the average of the numbers on the left side, and the average of the numbers in the middle but when it outputs the results, it’s not outputting back into a matrix.
Ex. user is asked for a number for Rows and Columns: input is 5 and 5
a 5×5 matrix is out put
but then i’m getting these results for the averages in a top to bottom fashion
50
50
71
65
61
48 64 57
59 26 61
43 63 20
The output I’m trying to achieve is
50
71 48 64 57
65 59 26 61
61 43 63 20
Obviously this isn’t a finished product seeing as how I have yet to program the averages for the rest of the matrix, but this formatting issue is driving me nuts.
heres the code:
#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 corner1 (int a[10][20], int n, int m)
{
int c[10][20];
int i,j;
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
if (i<=0 && j<=0)
{
c[i][j]=(a[i+1][j]+a[i][j+1])/2;
printf("%4d",c[i][j]);
}
}
}
printf("\n");
}
void middle(int a[10][20], int n, int m)
{
int c[10][20];
int i,j;
for (i=1;i<m-1;i++)
{
for (j=1;j<n-1;j++)
{
c[i][j]=(a[i-1][j]+a[i][j-1]+a[i+1][j]+a[i][j+1])/4;
printf("%4d",c[i][j]);
}
printf("\n");
}
}
void side1 (int a[10][20], int n, int m)
{
int c[10][20];
int i,j;
for (i=1;i<m;i++)
{
for (j=0;j<n-1;j++)
{
if (i<=1&&j>=0)
{
c[i][j]=(0+0+a[i-1][j]+a[i+1][j]+a[i][j+1])/3;
printf("%4d",c[i][j]);
printf("\n");
}
}
}
}
int main()
{
int a[10][20];
int m,n;
srand(time(NULL));
//User input
printf("please enter number of rows and columns\n");
scanf("%d %d", &m,&n);
fillArray(a,m,n);
printarray (a,m,n);
printf("The smoothed image is\n");
side1(a,m,n);
corner1(a,m,n);
middle (a,m,n);
getch();
return 0;
}
There are two solutions I can see off the top of my head:
Have corner1, side1 and middle store in an array. Print the array out when you’re done (instead of inside corner1, side1, and middle).
Iterate through each of the rows. Call side1 on the row, don’t print the newline, call middle on the row. This would be somewhat less efficient because of the numerous calls (for a larger image), and doesn’t reuse your printarray code so I would suggest you use option 1.