C++实现纯高斯模糊算法处理灰度图片(2)

unsigned int  winsize = (1 + (((int)ceil(3 * sigma)) * 2));  //窗的大小
    int *gaussKern = buildGaussKern(winsize, sigma); //构建高斯核,计算高斯系数
    winsize *= 1; //3改为1,高斯窗的宽度变为原来的1/3
    unsigned int  halfsize = winsize / 2;  //窗的边到中心的距离

unsigned char *tmpBuffer = (unsigned char*)malloc(width * height* sizeof(unsigned char));  //开辟新的内存存储处理高斯模糊后的数据

for (unsigned int h = 0; h < height; h++)    //外层循环,图像的高度
    {
        unsigned int  rowWidth = h * width;    //当前行的宽度为图像的高度乘以每行图像的数据所占的宽度。因为是按行存储的数组。

for (unsigned int w = 0; w < width; w++) //w+=channels,可以修改为w++,因为是单通道数据,而不是三通道数据
        {
            unsigned int rowR = 0;  //存储r分量的数据
            int * gaussKernPtr = gaussKern;//将高斯系数赋值给gaussKernPtr
            int whalfsize = w + width - halfsize;
            unsigned int  curPos = rowWidth + w;  //当前位置
            for (unsigned int k = 1; k < winsize;k++) // k += channels修改为k++
            {
                unsigned int  pos = rowWidth + ((k + whalfsize) % width);
                int fkern = *gaussKernPtr++;
                rowR += (pixels[pos] * fkern);  //当前像素值乘以高斯系数,rowR这了泛指单通道的当前像素点高斯处理后的数 
            }

tmpBuffer[curPos] = ((unsigned char)(rowR >> 8)); //除以256

}
    }
    halfsize = winsize / 2;
    for (unsigned int w = 0; w < width; w++)
    {
        for (unsigned int h = 0; h < height; h++)
        {
            unsigned    int col_all = 0;
            int hhalfsize = h + height - halfsize;
            for (unsigned int k = 0; k < winsize; k++)
            {
                col_all += tmpBuffer[((k + hhalfsize) % height)* width + w] * gaussKern[k];
            }
            pixelsout[h * width + w] = (unsigned char)(col_all >> 8);
        }
    }
    free(tmpBuffer);
    free(gaussKern);
}

int _tmain(int argc, _TCHAR* argv[])
{

const char* imagename = "C:\\Users\\Administrator.IES7LSEJAZ1GGRL\\Desktop\\PureGaussian-master\\GaussianBlur\\GaussianBlur\\InputName.bmp";
    //从文件中读入图像
    Mat img = imread(imagename);
    Mat dst = imread(imagename);
    Mat gray_img;
    Mat gray_dst;
    cvtColor(img, gray_img, CV_BGR2GRAY);
    cvtColor(dst, gray_dst, CV_BGR2GRAY);
    //如果读入图像失败
    if(img.empty())
    {
        fprintf(stderr, "Can not load image %s\n", imagename);
        return -1;
    }
    LARGE_INTEGER m_nFreq;
    LARGE_INTEGER m_nBeginTime;
    LARGE_INTEGER nEndTime;
    QueryPerformanceFrequency(&m_nFreq); // 获取时钟周期
    QueryPerformanceCounter(&m_nBeginTime); // 获取时钟计数
      GaussBlur1D(gray_img.data,gray_dst.data,gray_img.cols,gray_img.rows,2);
    QueryPerformanceCounter(&nEndTime);
    cout << (nEndTime.QuadPart-m_nBeginTime.QuadPart)*100/m_nFreq.QuadPart << endl;
    //显示图像
    imshow("原图像",gray_img);
    imshow("模糊图像", gray_dst);
    //此函数等待按键,按键盘任意键就返回
    waitKey();
    return 0;
}

算法实现效果:sigma=2.0

C++实现纯高斯模糊算法处理灰度图片

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/cf67204e9f4205393159d7c50687e9d3.html