gpt4 book ai didi

python - numpy掩码创建广播

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:26 25 4
gpt4 key购买 nike

我有 n 大小的图像 (n,row,col) 和 n 大小的 float (n,1)。

我想要做的是创建 (row, col) 大小的 0 和 1 掩码。 1 位于中心,0 位于边缘。 1 的大小取决于权重。

示例

>>> immask = np.zeros((2,8,8))
[[[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. 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. 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. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]]]

>>> multiplier = np.array([16./64,32./64])
[0.25 0.5 ]

#**insert magic here**
# expected result :
[[[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. 1. 1. 0. 0. 0.]
[0. 0. 0. 1. 1. 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.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]]]

有什么办法可以通过广播来做到这一点吗?不使用循环。提前致谢。

最佳答案

这个函数做了类似的事情:

import numpy as np

def make_masks(weights, rows, cols=None):
if cols is None:
cols = rows
# Add two dimensions to weights
w = np.asarray(weights)[:, np.newaxis, np.newaxis]
# Open grid of row and column coordinates
r, c = np.ogrid[-1:1:rows * 1j, -1:1:cols * 1j]
# Make masks where criteria is met
return (np.abs(r) <= w) & (np.abs(c) <= w)

# Test
masks = make_masks([0.25, 0.5], 8)
# Convert type as needed
masks_f = masks.astype(np.float32)
print(masks_f)

输出:

[[[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. 1. 1. 0. 0. 0.]
[0. 0. 0. 1. 1. 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.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 1. 1. 1. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]]]

编辑

制作圆形蒙版,函数如下:

import numpy as np

def make_circle_masks(weights, rows, cols=None):
if cols is None:
cols = rows
# Add two dimensions to weights
w = np.asarray(weights)[:, np.newaxis, np.newaxis]
# Open grid of row and column coordinates
r, c = np.ogrid[-1:1:rows * 1j, -1:1:cols * 1j]
# Arrays with distances to centre
d = r * r + c * c
# Make masks where criteria is met
return d <= w * w

关于python - numpy掩码创建广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com