[英]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.