简体   繁体   English

如何在python中从具有多个遮罩的单个图像创建每个图像包含一个实例遮罩的单独图像

[英]How to create separate images containing one instance mask per image from a single image with multiple masks in python

I have the following image: 我有以下图像:

在此处输入图片说明

Each mask is for an individual instance. 每个遮罩均用于单个实例。 I want to have separate images which will contain only one instance mask per image. 我想要单独的图像,每个图像仅包含一个实例蒙版。 Masks are not overlapping strictly. 口罩不严格重叠。 The outputs will be as like following: 输出将如下所示:

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

Thank You. 谢谢。

I have an answer to this. 我对此有一个答案。 The following code segment creates the desired output: 以下代码段创建所需的输出:

def create_separate_mask(path):
    # get all the masks
    for mask_file in glob.glob(path + '/*mask.png'): 
        mask = cv2.imread(mask_file, 1)
        # get masks labelled with different values
        label_im, nb_labels = ndimage.label(mask) 

        for i in range(nb_labels):

            # create an array which size is same as the mask but filled with 
            # values that we get from the label_im. 
            # If there are three masks, then the pixels are labeled 
            # as 1, 2 and 3.

            mask_compare = np.full(np.shape(label_im), i+1) 

            # check equality test and have the value 1 on the location of each mask
            separate_mask = np.equal(label_im, mask_compare).astype(int) 

            # replace 1 with 255 for visualization as rgb image

            separate_mask[separate_mask == 1] = 255 
            base=os.path.basename(mask_file)

            # give new name to the masks

            file_name = os.path.splitext(base)[0]
            file_copy = os.path.join(path, file_name + "_" + str(i+1) +".png") 
            cv2.imwrite(file_copy, separate_mask) 

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

相关问题 通过合并 python 中的两个其他蒙版来创建新的灰度蒙版图像 - create new grayscale mask image by merging two other masks in python 如何堆叠多个二进制掩码以创建用于多类分割的单个掩码? - How to stack multiple binary masks to create a single mask for multiclass segmentation? 如何将多个 numpy 掩码合并为 python 中的 1 个掩码? - How do I merge multiple numpy masks into 1 single mask in python? 使用 Python3 和 opencv 从掩码图像中获取中心掩码 - To get the center mask from an image of masks using Python3 and opencv 如何使用步幅从单个图像创建多个图像? - How to create multiple images from a single image using strides? 如何从 Python 中的蒙版分割图像创建轮廓(厚度可控)? - How to create an outline (with controllable thickness) from a mask segmentation image in Python? 如何从 PyTorch 中的 Mask R-CNN 预测中为图像生成准确的掩码? - How to generate accurate masks for an image from Mask R-CNN prediction in PyTorch? Python:从 2d 蒙版创建 3d 蒙版 - Python: Create a 3d mask from 2d masks 使用 OpenCV (Python) 的图像掩码 - Masks for image with OpenCV (Python) python PIL从单个图像文件访问多个图像 - python PIL acces multiple images from a single image file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM