c - 二维数组中值滤波

标签 c arrays algorithm median

我正在尝试编写实现 median filtering 的代码在一个二维数组上。 这是一张图片来说明:

IMAGE

程序从数组的开头开始。最大数组大小为 100。我知道我可以使用如下数组:

int a[100][100];

存储输入,我可以使用两个 for 循环遍历此数组的一部分,如下所示:

for(i=0;i<size_filter;i++)
for(j=0;j<size_filter;j++)
      temp[i][j]=a[i][j]     // not so sure

但是我怎样才能让这段代码遍历数组中每个元素的邻居,计算它们的中值,并用中值替换中心元素?


对于我正在尝试做的一些例子,假设输入是一个 5x5 矩阵,所以输入大小是 5。我想在它上面运行一个 3x3 中值滤波器,即每个元素都应该被替换通过它周围的 3x3 元素的中值。

程序从角索引 (0,0) 开始。对于这个索引,它扫描它周围的 3x3 区域(其中只有四个索引实际上位于输入数组中),其中包含值 0、0、1 和 0。这些值的中位数是 0,所以这就是代码应该输出这个数组索引。

在下图中,粗斜体 中的数字是中心单元格,普通粗体 数字是它在 3x3 中的相邻单元格它周围的区域:

0 0 0 0 0
1 0 0 1 0
1 1 0 0 0
0 1 1 0 0
0 0 0 0 0 

Here's another example, this time with the center index (0,1):

0 0 0 0 0
1 0 0 1 0
1 1 0 0 0
0 1 1 0 0
0 0 0 0 0 

This time, the elements in the 3x3 region (excluding those outside the input array) have the values 0, 0, 0, 1, 0, and 0, and again, their median is therefore 0.

Here's yet another example, this time from the middle of the input, at center index (3,2):

0 0 0 0 0
1 0 0 1 0
1 1 0 0 0
0 1 1 0 0
0 0 0 0 0 

This time, the elements within the 3x3 region have the values 1, 0, 0, 1, 1, 0, 0, 1, and 1, and their median in therefore 1.

Final example:

<size of array><size filter> <data>
8
3
0 0 0 0 0 0 0 0
0 5 0 0 6 0 0 0
0 0 0 0 0 7 0 0
0 0 0 0 5 0 0 0
0 0 0 5 6 0 0 0
0 0 8 5 5 0 0 0
0 0 0 7 0 0 9 0
0 0 0 0 0 0 0 0

Output:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 5 5 0 0 0
0 0 0 5 5 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

最佳答案

看起来您正在尝试实现二维 median filter .实现这种滤镜的直接方法是使用四个嵌套循环:两个外部循环覆盖整个图像的 x 和 y 坐标,两个内部循环覆盖中心像素的邻域。 p>

在代码中描述它可能比在文本中更容易描述,所以这里有一些 Python 风格的伪代码来说明:

# assumptions:
#  * image is a height x width array containing source pixel values
#  * filtered is a height x width array to store result pixel values in
#  * size is an odd number giving the diameter of the filter region

radius = (size - 1) / 2   # size = 3 -> radius = 1

for y from 0 to height-1:
    top = max(y - radius, 0)
    bottom = min(y + radius, height-1)

    for x from 0 to width-1:
        left = max(x - radius, 0)
        right = min(x + radius, width-1) 
        values = new list

        for v from top to bottom:
            for u from left to right:
                add image[v][u] to values

        filtered[y][x] = median(values)

将这段代码翻译成 C 语言留作练习。

还可以通过注意相邻数组单元格的邻域显着重叠来优化此代码,以便这些相邻单元格的值可以在外循环的连续迭代中重复使用。由于该算法在现代 CPU 上的性能基本上受到 RAM 访问延迟的限制,因此这种重用可以提供显着的加速,特别是对于大过滤器尺寸。

关于c - 二维数组中值滤波,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26870349/

相关文章:

c - 将时间修改标记写入文件顶部

arrays - 在mongodb中删除数组中的数组

Javascript 和 jQuery 数组未定义

javascript - 使用 Javascript 计算包含特定字符串的数组中唯一出现的次数

algorithm - 不是很大哦渐近符号{O(f(n)}算法可以拥有的最慢运行时间?(它给出了渐近上限,这意味着最慢的运行时间)

javascript - 确定图像在矩形内的最大可能尺寸

c - Valgrind 消息 : invalid file descriptor 1024 in syscall close()

c - 无法理解这段代码,如果 i 和 j 没有被使用,它是如何迭代 for 循环的?

c - 结构中的二维数组 - 可能吗?

python - 排列字符串以获得最大重叠