代码说明:将图片和标签转换成数组格式,并将标签二值化,然后相乘,以去除背景。
注意:图片和标签的尺寸应相同,且两者转换尺寸的处理方式应相同,否则两者的像素点不能相对应,导致结果图有误差。
代码:
import os
from PIL import Image
import numpy as np
def multiply_image_and_label(path_image, path_label): # 传入图片和标签的路径
pil_image = Image.open(path_image).convert('L')
pil_label = Image.open(path_label).convert('L')
assert pil_image.size == pil_label.size, 'The size of the picture and the label are not the same!'
array_image = np.array(pil_image)
array_label = np.array(pil_label)
# label二值化
array_label[array_label < 127] = 0
array_label[array_label >= 127] = 1
image_multiplied = np.multiply(array_image, array_label)
image_output = Image.fromarray(image_multiplied)
return image_output
if __name__ == "__main__":
dir_image = 'image' # 图片所在文件夹
dir_label = 'label' # 标签所在文件夹
dir_output = 'output' # 输出图片所在文件夹
if not os.path.exists(dir_output):
os.makedirs(dir_output)
list_label = os.listdir(dir_label)
i = 0
for file in list_label:
path_image = os.path.join(dir_image, file)
path_label = os.path.join(dir_label, file)
path_output = os.path.join(dir_output, file)
image_output = multiply_image_and_label(path_image, path_label)
image_output.save(path_output)
i += 1
print('Num of processed images:', i)
原图:
标签:
结果图: