Python去除图像白色背景

使用Pillow去除图像背景

安装依赖:

pip install pillow

实现步骤: 

  • 使用Pillow库加载图像,并将其转换为RGBA模式,以支持透明度。
  • 遍历图像的每个像素,检查其红色、绿色和蓝色值是否都高于预设的阈值。
  • 对于被视为白色的像素(即RGB值均高于阈值的像素),将其透明度设置为0(完全透明)。
  • 对于非白色像素,保留其原始透明度值(或不改变其透明度,因为它们在原始图像中可能已经是部分透明或有其他透明度值)。
  • 将修改后的图像保存为PNG格式,以保留透明度信息。

示例代码:

from PIL import Image

def remove_image_bg_pil(input_path, output_path):
    img = Image.open(input_path)
    img = img.convert("RGBA")
    data = img.getdata()

    threshold = 240
    # 创建一个新的图片数据列表
    new_data = []
    for item in data:
        # 将背景颜色设置为透明,这里假设背景颜色为白色,RGB值为(255, 255, 255)
        if item[0] >= threshold and item[1] >= threshold and item[2] >= threshold:
            new_data.append((255, 255, 255, 0))
        else:
            new_data.append(item)

    # 更新图片数据
    img.putdata(new_data)
    img.save(output_path, 'PNG')

使用OpenCV去除图像背景

安装依赖:

pip install opencv-python
pip install numpy

实现步骤:

  • 创建RGBA图像:将BGR图像转换为RGBA图像,初始时Alpha通道设置为全不透明(255)。
  • 定义白色阈值:设置一个阈值,用于判断哪些像素是“白色”。
  • 创建掩码:使用cv2.inRange函数创建一个掩码,将白色像素标记为0(透明),其他像素标记为255(不透明)。
  • 反转掩码:使用cv2.bitwise_not函数反转掩码,只对白色像素进行透明处理。
  • 应用掩码到Alpha通道:使用cv2.bitwise_and函数将掩码应用到Alpha通道,使白色像素的Alpha通道变为0(透明)。

示例代码:

import cv2
import numpy as np

def remove_image_bg_cv(input_path, output_path):
    # 读取图像
    img = cv2.imread(input_path)
    b, g, r = cv2.split(img)
    rgba = cv2.merge((b, g, r, 255 * np.ones(b.shape, dtype=b.dtype)))
    # 定义白色阈值
    white_threshold = 240
    # 创建一个掩码,将白色像素标记为0(透明),其他像素标记为255(不透明)
    mask = cv2.inRange(img, (white_threshold, white_threshold, white_threshold), (255, 255, 255))
    mask_inv = cv2.bitwise_not(mask)
    cv2.imwrite("output2/mask.png", mask_inv)
    # 将掩码应用到Alpha通道
    rgba[:, :, 3] = cv2.bitwise_and(rgba[:, :, 3], mask_inv)
    # 保存结果图像
    cv2.imwrite(output_path, rgba)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值