#include<iostream>
#define H 256
#define W 256

int main()
{
    unsigned char* grey;
    grey = new unsigned char[H * W];
    FILE* fp;
    fopen_s(&fp, "E:\\Digital image process\\lab-2\\第二次上机实验材料\\椒盐噪声.raw", "rb");
    if (fp)
    {
        fread(grey, sizeof(unsigned char), H * W, fp);
        fclose(fp);
    }
    int temph = 3, tempw = 3;
    unsigned char* newgrey;
    newgrey = new unsigned char[temph * tempw];
    unsigned char* result;
    result = new unsigned char[H * W];
    int i, j, k, q, m, n;
    unsigned char g;
    for (i = temph / 2; i < (H - temph / 2); i++)
    {
        for (j = tempw / 2; j < (W - tempw / 2); j++)
        {
            for (k = 0; k < temph; k++)
            {
                for (q = 0; q < tempw; q++)
                {
                    newgrey[k * tempw + q] = grey[(i - temph / 2 + k) * W + (j - tempw / 2 + q)];
                }
            }
            for (m = 0; m < temph * tempw - 1; m++)
            {
                for (n = m; n < temph * tempw; n++)
                {
                    if (newgrey[m] > newgrey[n])
                    {
                        g = newgrey[m];
                        newgrey[m] = newgrey[n];
                        newgrey[n] = g;
                    }
                }
            }
            result[i * W + j] = newgrey[temph * tempw / 2];
        }
    }
    FILE* pfile;
    fopen_s(&pfile, "E:\\Digital image process\\lab-2\\第二次上机实验材料\\中值滤波结果.raw", "wb");
    if (pfile)
    {
        fwrite(result, sizeof(unsigned char), H * W, pfile);
        fclose(pfile);
    }
}