如何申请形面具到numpy的阵列盘? [英] How to apply a disc shaped mask to a numpy array?
问题描述
我有一个这样的数组:
>>> np.ones((8,8))
array([[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.]])
我创建一个半径3因而盘状面膜:
I'm creating a disc shaped mask with radius 3 thus:
y,x = np.ogrid[-3: 3+1, -3: 3+1]
mask = x**2+y**2 <= 3**2
这给出了:
>> mask
array([[False, False, False, True, False, False, False],
[False, True, True, True, True, True, False],
[False, True, True, True, True, True, False],
[ True, True, True, True, True, True, True],
[False, True, True, True, True, True, False],
[False, True, True, True, True, True, False],
[False, False, False, True, False, False, False]], dtype=bool)
现在,我希望能够以这种面膜适用于我的阵列,使用任何元素作为中心点。
因此,例如,与(1,1)的中心点,我想获得像数组:
Now, I want to be able to apply this mask to my array, using any element as a center point. So, for example, with center point at (1,1), I want to get an array like:
>>> new_arr
array([[ True, True, True, True, 1., 1., 1., 1.],
[ True, True, True, True, True, 1., 1., 1.],
[ True, True, True, True, 1., 1., 1., 1.],
[ True, True, True, True, 1., 1., 1., 1.],
[ 1., True, 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.]])
有没有应用此面膜简单的方法?
Is there an easy way to apply this mask?
编辑:我不应该混布尔和漂浮 - 这是误导
>>> new_arr
array([[ 255., 255., 255., 255., 1., 1., 1., 1.],
[ 255., 255., 255., 255., 255., 1., 1., 1.],
[ 255., 255., 255., 255., 1., 1., 1., 1.],
[ 255., 255., 255., 255., 1., 1., 1., 1.],
[ 1., 255., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.]])
这是我更需要的结果。
This is more the result I require.
数组[面具] = 255
array[mask] = 255
将面膜使用中心点(0 +半径,0 +半径)的阵列。
will mask the array using centre point (0+radius,0+radius).
不过,我希望能够把任何尺寸面具在任何时候(Y,X),并自动裁剪以适合。
However, I'd like to be able to place any size mask at any point (y,x) and have it automatically trimmed to fit.
推荐答案
我会做这样的,其中(A,B)是你的面具的中心:
I would do it like this, where (a, b) is the center of your mask:
import numpy as np
a, b = 1, 1
n = 7
r = 3
y,x = np.ogrid[-a:n-a, -b:n-b]
mask = x*x + y*y <= r*r
array = np.ones((n, n))
array[mask] = 255
这篇关于如何申请形面具到numpy的阵列盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!