python-图像处理:图片与标签相乘以去除背景

代码说明:将图片和标签转换成数组格式,并将标签二值化,然后相乘,以去除背景。

注意:图片和标签的尺寸应相同,且两者转换尺寸的处理方式应相同,否则两者的像素点不能相对应,导致结果图有误差。

代码:

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)

原图:
在这里插入图片描述
标签:
在这里插入图片描述
结果图:
在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值