简体   繁体   English

根据不同大小的掩码数组过滤 Numpy 数组

[英]Filter Numpy array based on different size mask array

I'm trying to mark regions of an image array (224x224) to be ignored based on the value of a segmentation network's class mask (16x16).我正在尝试根据分割网络的 class 掩码 (16x16) 的值来标记要忽略的图像数组 (224x224) 的区域。 Previous processing means that unwanted regions will be labelled as -1.先前的处理意味着不需要的区域将被标记为 -1。 I want to be able to set the value of all regions of the image where the class mask reports -1 to some nonsense value (say, 999), but maintain the shape of the array (224x224).我希望能够设置图像的所有区域的值,其中 class 掩码将 -1 报告为一些无意义的值(例如,999),但保持数组的形状(224x224)。 A concise example of what I mean is below, using a 4x4 image and 2x2 mask.下面是我的意思的一个简洁示例,使用 4x4 图像和 2x2 蒙版。

# prefilter
image = 1 2 3 4
        5 6 7 8
        9 1 2 3
        4 5 6 7

mask  = -1 4
        -1 5

# postfilter

image_filtered = 999 999 3 4
                 999 999 7 8
                 999 999 2 3
                 999 999 6 7

Is there an efficient way to do this modification?

Here's some code I got to work.这是我必须工作的一些代码。 It does require the mask and the image to have the same aspect ratio, and be integer multiples of each others sizes.它确实要求掩码和图像具有相同的纵横比,并且是彼此大小的 integer 倍数。

import numpy as np

image = np.array([[1,2,3,4],
                  [5,6,7,8],
                  [9,1,2,3],
                  [4,5,6,7]])

mask = np.array([[-1,4],
                 [-1,5]])

def mask_image(image, mask, masked_value):
    
    scale_factor = image.shape[0]//mask.shape[0] # how much the mask needs to be scaled up by to match the image's size
    
    resized_mask = np.kron(mask, np.ones((scale_factor,scale_factor))) # resize the mask (magic)

    return(np.where((resized_mask==-1),masked_value,image)) # where the mask==-1, return the masked value, else return the value of the original array.
    
print(mask_image(image, mask, 999))

I used np.kron to resize an array after seeing this answer .看到这个答案后,我使用np.kron来调整数组的大小。

This function is extremely fast, it took ~2 sec to mask a 1920x1080 image with a 1920x1080 mask .这个 function 速度非常快,用 1920x1080 掩码遮盖 1920x1080 图像大约需要 2 秒

EDIT: Use what @Jérôme Richard said in their comment.编辑:使用@Jérôme Richard 在他们的评论中所说的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM