用内核平滑2D numpy数组 [英] Smoothing a 2-D Numpy Array with a Kernel
问题描述
假设我有一个(m x n)2-d numpy数组,它们只是0和1.我想通过在阵列上运行例如3x3内核并获取该内核中的多数值来平滑"阵列.对于边缘的值,我将忽略丢失"的值.
Suppose I have an (m x n) 2-d numpy array that are just 0's and 1's. I want to "smooth" the array by running, for example, a 3x3 kernel over the array and taking the majority value within that kernel. For values at the edges, I would just ignore the "missing" values.
例如,假设数组看起来像
For example, let's say the array looked like
import numpy as np
x = np.array([[1, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
从左上角"1"开始,以左上角第一个元素为中心的3 x 3内核将缺少第一行和第一列.我要处理的方法就是忽略它,并考虑剩下的2 x 2矩阵:
Starting at the top left "1", a 3 x 3 kernel centered at the first top left element, would be missing the first row and first column. The way I want to treat that is just ignore that and consider the remaining 2 x 2 matrix:
1 0
0 0
在这种情况下,多数值为0,因此将该元素设置为0.对所有元素重复此操作,我想要的结果二维数组为:
In this case, the majority value is 0, so set that element to 0. Repeating this for all elements, the resulting 2-d array I would want is:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 0
0 0 1 1 1 1 1 0
0 0 1 1 1 1 1 0
0 0 1 1 1 1 1 0
0 0 1 1 1 1 0 0
0 0 0 0 0 0 0 0
我如何做到这一点?
推荐答案
您可以使用3x3 内核.nofollow noreferrer> skimage.morphology.square
:
You can use skimage.filters.rank.majority
to assign to each value the most occuring one within its neighborhood. The 3x3
kernel can be defined using skimage.morphology.square
:
from skimage.filters.rank import majority
from skimage.morphology import square
majority(x.astype('uint8'), square(3))
array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
注意:您需要使用 scikit-image
的最新稳定版本,以实现多数
.更多此处
Note: You'll need the latest stable version of scikit-image
for majority
. More here
这篇关于用内核平滑2D numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!