用python中的反射填充有效地填充蒙版数组值

时间:2019-01-23 05:55:25

标签: python python-3.x numpy data-science

我有一个正方形矩阵(图像),在一个区域中带有蒙版值。遮罩对应于(总是)靠近边界的区域中的缺失值。我想创建一个新图像,其中将遮罩的值替换为存在实际图像值的值的反射填充。如何在python中这样做?

在下面的示例中,我想用存在数据的中间面板的反射图像替换(左侧面板)黄色区域。结果应该类似于右面板图像(此处的填充不适合我想要的反射填充,因为我只是使用过幼稚的食谱right_image = np.where(temp.mask,middle_image[::-1,::-1],middle_image)

enter image description here

编辑:我尝试逐行横切图像,并使用numpy反射填充,以及下面的代码,但这不起作用:

# Row Reflect 
# Here out_image is the original image, where -2 is no data value
xx = []
for i in range(6000): # Number of rows
    temp1 = np.ma.array(out_image[0,i,:],mask= out_image[0,i,:]==-2) # Create mask per row, -2 is the masked value
    edges = ma.flatnotmasked_edges(temp1) # Find edges
    #if edges is not None:
    xx += [np.expand_dims(np.pad(temp1.data[edges[0]:edges[1]],((edges[0],temp1.shape[0]-edges[1])),mode='reflect'),0)]
out = np.concatenate(xx)
#out = out.reshape(2000,2000)

结果不正确。 enter image description here

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您想向遮罩区域添加反射(旋转180°)。您可以使用scipy.ndimage.rotatedocs)并添加两个图像。

这样的事情有用吗?:

from scipy.ndimage import rotate
# sample mask for a 768 * 1024 image
line = lambda x: 400 - 200 * x/800   
mask = np.indices(im.shape[:2])
mask = line(mask[0])<mask[1]

plt.imshow(im*mask[:,:,None])
plt.show()

im2=rotate(im, 180) 
plt.imshow(im*mask[:,:,None] + im2*~mask[:,:,None])
plt.show()

Original Image Output