Python 将值分配到图像数组的随机块的有效方法?
我有一个3d numpy阵列。这是一个二维正方形图像阵列,大小都相同。我的任务是阻止图像的随机方形补丁(将所有像素值设置为0)。在我只有一张图片的情况下,我可以想出如何做到这一点,如下所示Python 将值分配到图像数组的随机块的有效方法?,python,numpy,image-processing,Python,Numpy,Image Processing,我有一个3d numpy阵列。这是一个二维正方形图像阵列,大小都相同。我的任务是阻止图像的随机方形补丁(将所有像素值设置为0)。在我只有一张图片的情况下,我可以想出如何做到这一点,如下所示 x = np.random.randint(image_width - size) y = np.random.randint(image_width - size) image[x:x + size, y:y + size] = 0 其中size是被封锁区域的大小。我不知道如何有效地对2d图像阵列执行此技
x = np.random.randint(image_width - size)
y = np.random.randint(image_width - size)
image[x:x + size, y:y + size] = 0
其中size是被封锁区域的大小。我不知道如何有效地对2d图像阵列执行此技术,其中,为每个图像随机生成遮挡面片(不一定是阵列中每个图像中遮挡的相同面片)。我对我必须处理的所有新的索引工具(广播、奇特的索引等)感到有点迷茫,我想知道是否有一种快速而简单的方法可以做到这一点,谢谢。我目前的方法是使用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))
在某个时刻,但我不知道在哪里。我们可以利用based来获得滑动窗口
样本运行
设置输入-
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]]])
所以,
图像
是(N,W,H)
,即N个图像?此外,所有图像的大小是否相同(W,H)?图像数组为(N,W,H)。这些图像都是同样大小的,都是方形的。
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]]])