c - 请解释此代码如何去除图像中的噪声

标签 c image-processing

下面的代码实际上是如何去除图像中的噪声的?我试图了解发生了什么,但似乎无法掌握整体思路。我已经尝试过了并且有效(但效果不佳)。请给一个大概的解释。谢谢。

void averageFilter(PIXEL_ARRAY* img, PIXEL_ARRAY* orig_img, int N) 
{

  int i, j, n, m;
  int red_avg, blue_avg, green_avg;
  int radius, out_of_bounds, idx, curr_idx;
  int32_t pixel;

  if (N % 2 == 0) {
    printf("ERROR: Please use an odd sized window\n");
    exit(1);
  }

  radius = N / 2;

  for (i = 0; i < img->sizeY; i++) {
    for (j = 0; j < img->sizeX; j++) {
      out_of_bounds = 0;

      red_avg = 0;
      blue_avg = 0;
      green_avg = 0;

      for (n = i - radius; n <= i + radius; n++) {

    for (m = j - radius; m <= j + radius; m++) {
      if (n < 0 || m < 0 || n >= img->sizeY || m >= img->sizeX) {
        out_of_bounds++;
        continue;
      }
      idx = m + n * img->sizeX;
      /* Shift, mask and add */


      red_avg += ((orig_img->data[idx] >> 16) & 0xFF);
      green_avg += ((orig_img->data[idx] >> 8) & 0xFF);
      blue_avg += (orig_img->data[idx] & 0xFF);

    }
      }

      /* Divide the total sum by the amount of pixels in the window */
      red_avg /= (N * N - out_of_bounds);
      green_avg /= (N * N - out_of_bounds);
      blue_avg /= (N * N - out_of_bounds);

      /* Set the average to the current pixel */
      curr_idx = j + i * img->sizeX;
      pixel = (red_avg << 16) + (green_avg << 8) + blue_avg;
      img->data[curr_idx] = pixel;
    }
  }
}

最佳答案

for (i = 0; i < img->sizeY; i++) {
    for (j = 0; j < img->sizeX; j++) {`

对于网格中的所有像素...

for (n = i - radius; n <= i + radius; n++) {
 for (m = j - radius; m <= j + radius; m++) {

访问我们像素的 radius 范围内的位置...

 if (n < 0 || m < 0 || n >= img->sizeY || m >= img->sizeX) {
        out_of_bounds++;
        continue;

(记住我们找到了多少)

  idx = m + n * img->sizeX;

当我们找到一个位置时,我们会

  • n 向上像素(主像素-Y +/- 半径),
  • m 像素横跨(主像素-X +/- 半径), 所以……

  • n 行 sizeX 像素,

  • 为该行加上 m,是...

idx:我们所在位置的像素索引

 red_avg += ((orig_img->data[idx] >> 16) & 0xFF);
 green_avg += ((orig_img->data[idx] >> 8) & 0xFF);
 blue_avg += (orig_img->data[idx] & 0xFF);

从我们访问的每个位置统计原始图像的 RGB 数据

   /* Divide the total sum by the amount of pixels in the window */
   red_avg /= (N * N - out_of_bounds);
   green_avg /= (N * N - out_of_bounds);
   blue_avg /= (N * N - out_of_bounds);
   /* Set the average to the current pixel */

...平均每个主像素的 radius 内的所有位置...

      curr_idx = j + i * img->sizeX;
      pixel = (red_avg << 16) + (green_avg << 8) + blue_avg;
      img->data[curr_idx] = pixel;

...并将输出文件中的 main-pixel-index 设置为平均值。

关于c - 请解释此代码如何去除图像中的噪声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554556/

相关文章:

c - Strtok 字符串并将其传递给另一个函数

python - 从图像中提取文本

opencv - 图像处理中的工业级前景/背景分离

c# - 从一个位置拍摄的几张图像制作全景图像

c++ - 找不到包 'gdk-pixbuf-2.0'

c - Perlin 噪声函数 - 值超出范围

c - C 中具有固定大小缓冲区的 read() 函数无法返回预期结果

c - 访问 char 和 int 参数

c++ - 使用 OpenCV 和 C++ 将图像帧拆分为 8*8 用于 DCT

python - 如何在 python 中扩展 1D FFT 代码来计算图像(2D)的 FFT?