gpt4 book ai didi

python - 将值分配给图像数组的随机 block 的有效方法?

转载 作者:行者123 更新时间:2023-12-01 09:02:40 24 4
gpt4 key购买 nike

我有一个 3d numpy 数组。它是一个二维方形图像的数组,所有图像的大小都相同。我的任务是遮挡图像的随机方形 block (将所有像素值设置为 0)。我可以弄清楚在我只有 1 张图像的情况下该怎么做

x = np.random.randint(image_width - size)
y = np.random.randint(image_width - size)
image[x:x + size, y:y + size] = 0

其中 size 是遮挡区域的大小。我不确定如何有效地对二维图像数组执行此技术,其中为每个图像随机生成被遮挡的补丁(不一定在数组中的每个图像中被遮挡的相同补丁)。我对必须处理的所有新索引工具(广播、花式索引等)感到有点迷失,并且想知道是否有一种快速而简单的方法可以做到这一点,谢谢。目前我的方法是使用 for 循环简单地迭代每个图像,一次处理一张图像,但我想知道 numpy 是否足够强大,能够以某种方式一次性完成所有图像。我确实意识到我需要使用

x_array = np.random.randint(image_width - size, size=len(image_array))
y_array = np.random.randint(image_width - size, size=len(image_array))

在某个时刻,但我不知道在哪里。

最佳答案

我们可以利用np.lib.stride_tricks.as_strided基于scikit-image's view_as_windows获得滑动 window 。 More info on use of as_strided based view_as_windows .

from skimage.util.shape import view_as_windows

# Get sliding windows as views
w = view_as_windows(image_array,(1,size,size))[...,0,:,:]

# Index with advanced-indexing into windows array and
# assign into it, thus reassigning into input array directly being views
w[np.arange(len(x_array)),x_array,y_array] = 0

示例运行

设置输入 -

In [60]: image_array # input array
Out[60]:
array([[[54, 57, 74, 77, 77],
[19, 93, 31, 46, 97],
[80, 98, 98, 22, 68],
[75, 49, 97, 56, 98]],

[[91, 47, 35, 87, 82],
[19, 30, 90, 79, 89],
[57, 74, 92, 98, 59],
[39, 29, 29, 24, 49]],

[[42, 75, 19, 67, 42],
[41, 84, 33, 45, 85],
[65, 38, 44, 10, 10],
[46, 63, 15, 48, 27]]])

In [68]: size
Out[68]: 2

# x and y starting indices for 0s assignments
In [65]: x_array
Out[65]: array([1, 0, 1])

In [66]: y_array
Out[66]: array([2, 2, 0])

使用建议的解决方案 -

In [62]: w = view_as_windows(a,(1,size,size))[...,0,:,:]

In [63]: w[np.arange(len(x_array)),x_array,y_array] = 0

In [64]: image_array # verify
Out[64]:
array([[[54, 57, 74, 77, 77], # start at (1,2)
[19, 93, 0, 0, 97],
[80, 98, 0, 0, 68],
[75, 49, 97, 56, 98]],

[[91, 47, 0, 0, 82], # start at (0,2)
[19, 30, 0, 0, 89],
[57, 74, 92, 98, 59],
[39, 29, 29, 24, 49]],

[[42, 75, 19, 67, 42], # start at (1,0)
[ 0, 0, 33, 45, 85],
[ 0, 0, 44, 10, 10],
[46, 63, 15, 48, 27]]])

关于python - 将值分配给图像数组的随机 block 的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353944/

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