我有一个图像表示为一个数组(img),我想制作许多图像副本,并在每个副本中清零图像的不同方块(在第一个副本中0:2,0:2, 0:2在下一个拷贝归零0:2,3:5等)。我已经使用np.broadcast_to来创建图像的多个副本,但是我无法索引图像的多个副本,以及图像中的多个位置将图像中的方块清零。
我想我正在寻找像skimage.util.view_as_blocks这样的东西,但我需要能够写入原始数组,而不仅仅是阅读。
这背后的想法是通过神经网络传递图像的所有副本。执行最差的副本应该是我试图在其零位置识别的类(图片)。
img = np.arange(10*10).reshape(10,10)
img_copies = np.broadcast_to(img, [100, 10, 10])
z = np.zeros(2*2).reshape(2,2)
由于
答案 0 :(得分:0)
我想我已经破解了!以下是使用masking
重新整形的数组中6D
的方法 -
def block_masked_arrays(img, BSZ):
# Store shape params
m = img.shape[0]//BSZ
n = m**2
# Make copies of input array such that we replicate array along first axis.
# Reshape such that the block sizes are exposed by going higher dimensional.
img3D = np.tile(img,(n,1,1)).reshape(m,m,m,BSZ,m,BSZ)
# Create a square matrix with all ones except on diagonals.
# Reshape and broadcast it to match the "blocky" reshaped input array.
mask = np.eye(n,dtype=bool).reshape(m,m,m,1,m,1)
# Use the mask to mask out the appropriate blocks. Reshape back to 3D.
img3D[np.broadcast_to(mask, img3D.shape)] = 0
img3D.shape = (n,m*BSZ,-1)
return img3D
示例运行 -
In [339]: img
Out[339]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
In [340]: block_masked_arrays(img, BSZ=2)
Out[340]:
array([[[ 0, 0, 2, 3],
[ 0, 0, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[ 0, 1, 0, 0],
[ 4, 5, 0, 0],
[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 0, 0, 10, 11],
[ 0, 0, 14, 15]],
[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 0, 0],
[12, 13, 0, 0]]])