我需要为一组图像创建随机布尔掩码。每个掩码是具有6个随机正方形的1数组,其中值为0。正方形的长度是56像素。可以使用以下代码创建掩码:
mask = np.ones(shape=(3, h, w))
for _ in range(6):
x_coordinate = np.random.randint(0, w)
y_coordinate = np.random.randint(0, h)
mask[:, x_coordinate: x_coordinate + 56, y_coordinate: y_coordinate + 56] = 0现在我想做的棘手的事情是对一批图像的这个过程进行矢量化。这有可能吗?现在,我只是对批处理中的每个图像使用一个简单的for循环调用这个函数,但我想知道是否有一种方法可以完全避免for循环。
另外:批次中的每个图像的蒙版必须不同(不能对每个图像使用相同的蒙版)
发布于 2020-03-20 09:09:08
我们可以利用基于np.lib.stride_tricks.as_strided的scikit-image's view_as_windows来获得滑动窗口,从而在这里解决我们的问题。More info on use of as_strided based view_as_windows。
作为views-based,它将是最高效的!
from skimage.util.shape import view_as_windows
N = 3 # number of images in the batch
image_H,image_W = 5,7 # edit to image height, width
bbox_H,bbox_W = 2,3 # edit to window height, width to be set as 0s
w_off = image_W-bbox_W+1
h_off = image_H-bbox_H+1
M = w_off*h_off
R,C = np.unravel_index(np.random.choice(M, size=N, replace=False), (h_off, w_off))
mask_out = np.ones(shape=(N, image_H, image_W), dtype=bool)
win = view_as_windows(mask_out, (1, bbox_H,bbox_W))[...,0,:,:]
win[np.arange(len(R)),R,C] = 0如果您不介意重复掩码,只需在代码中使用replace=True即可。
带有给定输入参数的示例输出-
In [6]: mask_out
Out[6]:
array([[[ True, True, True, True, True, True, True],
[ True, True, False, False, False, True, True],
[ True, True, False, False, False, True, True],
[ True, True, True, True, True, True, True],
[ True, True, True, True, True, True, True]],
[[ True, True, True, True, True, True, True],
[ True, False, False, False, True, True, True],
[ True, False, False, False, True, True, True],
[ True, True, True, True, True, True, True],
[ True, True, True, True, True, True, True]],
[[ True, True, True, True, True, True, True],
[ True, True, True, True, True, True, True],
[False, False, False, True, True, True, True],
[False, False, False, True, True, True, True],
[ True, True, True, True, True, True, True]]])https://stackoverflow.com/questions/60765597
复制相似问题