#include<stdio.h>
#include<stdlib.h>
#define height 256
#define width 256
typedef unsigned char BYTE;
void main()
{
int i,j,x,y,k,l;
int size =3;//마스크크기 3x3
int temp;
unsigned char *mmask;
double temp_sum;
double mask[3][3] = { {1.0/9, 1.0/9, 1.0/9},
{1.0/9, 1.0/9, 1.0/9},
{1.0/9, 1.0/9, 1.0/9} };
mmask = (unsigned char*) calloc(size*size,sizeof(char));
FILE *F_I_true = fopen("lena.raw","rb");
FILE *F_I_noisy = fopen("lena_noisy.raw","rb");
FILE *F_O = fopen("lena_denoise.raw","wb");
BYTE* MemTrue = new BYTE [height*width];
BYTE* MemIn = new BYTE [height*width];
BYTE* MemOut = new BYTE [height*width];
fread(MemTrue, sizeof(BYTE), height*width, F_I_true); // use only for the performance evaluation
fread(MemIn, sizeof(BYTE), height*width, F_I_noisy); //
// Apply your image restortaion algorithm here
for(j=0; j<height; j++)
{
for(i =0; i<width; i++)
{
for(k = 0; k<size; k++)
{
x =j+k - (int)((size-1)/2);
if(x<0) x = 0; ///경계면
if(x>height -1) x = height-1;
for(l=0;l<size;l++)
{
y=i+l - (int)((size-1)/2);
if(y<0) y =0; ///경계면
if(y>width-1) y = width -1;
mmask[k*size+l]=MemIn[x*width+y];
}
}
///////////////버블정렬//////////////////
for(int a=0; a<size*size;a++)
{
for(int b=0;b<size*size-a; b++)
{
if(mmask[b]>mmask[b+1])
{
temp = mmask[b];
mmask[b]=mmask[b+1];
mmask[b+1]=temp;
}
}
}
temp=mmask[(size*size-1)/2];//temp에 중간값을 넣는다.
if(temp<0) temp =0;
if(temp>255) temp =255;
MemOut[j*width+i]=(unsigned char)temp;
}
}
// The following code is for 3x3 average filter
//for( j=1; j< height-1; j++ )
//{
// for( i=1; i < width-1; i++ )
// {
// temp_sum = 0.0;
// for( x=-1; x<=1; x++ )
// {
// for( y=-1; y<=1; y++ )
// {
// temp_sum += (mask[x+1][y+1]*MemIn[(j+x)*width +(i+y)]);
// }
// }
// MemOut[j*width+i] = temp_sum;
// }
//}
///////////////////////////////////////////////////////////////
///////////max/min 은 쓰지않는걸로///////////
// unsigned char Max,Min;
//
//for(j =0; j<height; j++)
//{
// for(i = 0; i<width; i++)
// {
// Min = 255;
// Max = 0;
// for(int k =0; k<size;k++)
// {
// x = j+k-(int)((size-1)/2);
// if(x<0)x=0; ///경계면
// if(x>height -1) x=height-1;
// for(int l=0; l<size;l++)
// {
// y = i+l-(int)((size-1)/2);
// if(y<0) y=0; ///경계면
// if(y>width-1) y=width-1;
// if(Min>Mem[x*width+y]) Min=Mem[x*width+y];
// if(Max<Mem[x*width+y]) Max=Mem[x*width+y];
// }
// }
// MemOut[j*width+i] = Min;
// MemOut[j*width+i] = Max;
// }
//}
temp_sum = 0;
// Evaluate the performance
for( j=0; j< height; j++ )
{
for( i=0; i < width; i++ )
{
temp_sum += abs(MemTrue[j*width+i]- MemOut[j*width+i]);
}
}
temp_sum /= (height*width);
printf("Distortion: %f\n", temp_sum);
///////////////////////////////////////////////////////////////
fwrite(MemOut,sizeof(BYTE),height*width, F_O);
delete MemTrue;
delete MemIn;
delete MemOut;
fclose(F_I_true);
fclose(F_I_noisy);
fclose(F_O);
}