答案 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)