如何从 python 中具有多个蒙版的单个图像创建每个图像包含一个实例蒙版的单独图像
How to create separate images containing one instance mask per image from a single image with multiple masks in python
我有以下图片:
每个掩码都用于一个单独的实例。我想要单独的图像,每个图像只包含一个实例掩码。面具没有严格重叠。输出将如下所示:
谢谢。
我有一个答案。以下代码段创建所需的输出:
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)
我有以下图片:
每个掩码都用于一个单独的实例。我想要单独的图像,每个图像只包含一个实例掩码。面具没有严格重叠。输出将如下所示:
谢谢。
我有一个答案。以下代码段创建所需的输出:
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)