简体   繁体   English

C ++图像处理:均匀的平滑操作使图像更暗

[英]C++ Image Processing: Uniform Smoothing Operation Makes Image Darker

I'm trying to reduce noise in an image by creating a 2D uniform smoothing algorithm in C++. 我正在尝试通过在C ++中创建2D均匀平滑算法来减少图像中的噪声。 The function I'm using for each pixel computes the average value of neighboring pixels within a square odd window and uses that as the new value. 我为每个像素使用的函数计算平方奇数窗内相邻像素的平均值,并将其用作新值。

Whenever I run the code, however, the pixels in the new image become darker (a pixel value of 255=white, and 0=black). 但是,无论何时运行代码,新图像中的像素都会变暗(像素值255 =白色,0 =黑色)。 Here is the function for obtaining the new pixel value: 这是获取新像素值的函数:

int utility::windowAverage (image &src, int x, int y, int window_size)
{
    int sum = 0;
    int avg;
    for(int i = x-(window_size/2); i < x+(window_size/2);++i)
    {
        for(int j = y-(window_size/2); j < y+(window_size/2);++j)
        {
            sum += src.getPixel(i,j);
        }
    }

    avg = sum/(window_size*window_size);
    return avg;
}

The parameter image &src is the source image, and the function src.getPixel(i,j) returns an integer from 0 to 255 representing the brightness of the pixel at the specified coordinates (i,j). 参数image &src是源图像,函数src.getPixel(i,j)返回0到255之间的整数,表示指定坐标(i,j)处像素的亮度。

I am running the code over gray-level images of the .pgm format. 我正在.pgm格式的灰度图像上运行代码。

How can I smooth the image while maintaining the same brightness? 如何在保持相同亮度的同时平滑图像?

The problem is that you are not actually adding the pixels in a window with the dimension of windows_size*windows_size, but you are missing the last pixel in each dimension when computing sum . 问题是您实际上没有在窗口尺寸为windows_size * windows_size的像素中添加像素,但是在计算sum时,每个尺寸的最后一个像素都丢失了。

You can fix this by using <= instead of < in both of your for loops. 您可以通过在两个for循环中使用<=代替<来解决此问题。


Example of what is going wrong for window_size = 3 and x=0 and y=0 : window_size = 3x=0y=0出问题的示例

The integer division by 2 in your for loops is floored, which means that your loops would become for (int i=-1; i < 1; i++) . for循环中的整数除以2是有底数的,这意味着您的循环将变为for (int i=-1; i < 1; i++) This obviously only loops over the (two) pixles -1 and 0 in the given direction, but you still divide by the full window_size of 3, which makes the image darker (in this case by one third if it has constant color values). 显然,这仅沿给定方向在(两个)像素-1和0上循环,但您仍需将window_size的完整值除以3,这会使图像更暗(在这种情况下,如果颜色值恒定,则为三分之一)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM