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

时间:2019-07-24 22:40:45

标签: python image image-processing image-segmentation

我有以下图像:

enter image description here

每个掩码都针对单个实例。我想要单独的图像,每个图像仅包含一个实例蒙版。口罩不严格重叠。输出将如下所示:

enter image description here enter image description here enter image description here

谢谢。

1 个答案:

答案 0 :(得分:0)

我对此有一个答案。以下代码段创建所需的输出:

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)