python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python图片背景转换

python将图片透明背景转为白色背景的两种方法

作者:去追风,去看海

这篇文章主要为大家详细介绍了python如何使用opencv2和PIL实现将图片透明背景转换成白色背景功能,感兴趣的小伙伴可以跟随小编一起学习一下

方法一:使用OpenCV的函数封装

安装库

pip install opencv-python

实现代码

import cv2
import numpy as np

def convert_transparent_to_white_opencv(input_image_path, output_image_path):
    """
    将透明背景的图片转换为白色背景,使用OpenCV实现。

    参数:
    input_image_path: str,输入图片的路径
    output_image_path: str,输出图片的路径

    返回:
    无
    """
    # 读取带透明背景的图片(假设图片是PNG格式)
    img = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)

    # 检查是否读取成功
    if img is None:
        raise ValueError(f"Image at path {input_image_path} could not be read.")

    # 分离RGBA通道
    b, g, r, a = cv2.split(img)

    # 创建一个与Alpha通道大小相同的全白背景
    white_background = np.ones_like(a) * 255

    # 将Alpha通道归一化到0-1范围
    a = a / 255.0

    # 按照Alpha通道的透明度混合原图和白色背景
    r = r * a + white_background * (1 - a)
    g = g * a + white_background * (1 - a)
    b = b * a + white_background * (1 - a)

    # 合并BGR通道
    result = cv2.merge((b, g, r))

    # 保存处理后的图片
    cv2.imwrite(output_image_path, result)

# 示例调用
convert_transparent_to_white_opencv('input_image.png', 'output_image_opencv.png')

方法二:使用PIL的函数封装

安装库

pip install pillow

完整代码

from PIL import Image

def convert_transparent_to_white_pil(input_image_path, output_image_path):
    """
    将透明背景的图片转换为白色背景,使用PIL实现。

    参数:
    input_image_path: str,输入图片的路径
    output_image_path: str,输出图片的路径

    返回:
    无
    """
    # 读取带透明背景的图片(假设图片是PNG格式)
    img = Image.open(input_image_path).convert("RGBA")

    # 创建一个与原图片大小相同的白色背景
    white_background = Image.new("RGB", img.size, (255, 255, 255))

    # 将原图片粘贴到白色背景上,并使用Alpha通道作为掩码
    white_background.paste(img, (0, 0), img)

    # 保存处理后的图片
    white_background.save(output_image_path)

# 示例调用
convert_transparent_to_white_pil('input_image.png', 'output_image_pil.png')

详细解释

OpenCV方法函数封装

PIL方法函数封装

通过上述封装函数,可以更方便地将带透明背景的图片转换为白色背景的图片。

可以将带透明背景的图片转换为任意颜色背景的图片,并在任意颜色背景之间进行转换。以下是使用OpenCV和PIL的方法,并进行了函数封装,允许用户指定任意背景颜色。

1, 使用OpenCV的函数封装

import cv2
import numpy as np

def convert_transparent_to_color_opencv(input_image_path, output_image_path, bg_color=(255, 255, 255)):
    """
    将透明背景的图片转换为任意颜色背景,使用OpenCV实现。

    参数:
    input_image_path: str,输入图片的路径
    output_image_path: str,输出图片的路径
    bg_color: tuple,背景颜色(默认为白色 (255, 255, 255))

    返回:
    无
    """
    # 读取带透明背景的图片(假设图片是PNG格式)
    img = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)

    # 检查是否读取成功
    if img is None:
        raise ValueError(f"Image at path {input_image_path} could not be read.")

    # 分离RGBA通道
    b, g, r, a = cv2.split(img)

    # 创建一个与Alpha通道大小相同的指定颜色背景
    background = np.ones_like(a) * np.array(bg_color[::-1], dtype=np.uint8)[:, None, None]

    # 将Alpha通道归一化到0-1范围
    a = a / 255.0

    # 按照Alpha通道的透明度混合原图和背景
    r = r * a + background[0] * (1 - a)
    g = g * a + background[1] * (1 - a)
    b = b * a + background[2] * (1 - a)

    # 合并BGR通道
    result = cv2.merge((b, g, r))

    # 保存处理后的图片
    cv2.imwrite(output_image_path, result)

# 示例调用
convert_transparent_to_color_opencv('input_image.png', 'output_image_opencv.png', bg_color=(0, 128, 255))

2, 使用PIL的函数封装

from PIL import Image

def convert_transparent_to_color_pil(input_image_path, output_image_path, bg_color=(255, 255, 255)):
    """
    将透明背景的图片转换为任意颜色背景,使用PIL实现。

    参数:
    input_image_path: str,输入图片的路径
    output_image_path: str,输出图片的路径
    bg_color: tuple,背景颜色(默认为白色 (255, 255, 255))

    返回:
    无
    """
    # 读取带透明背景的图片(假设图片是PNG格式)
    img = Image.open(input_image_path).convert("RGBA")

    # 创建一个与原图片大小相同的指定颜色背景图像
    background = Image.new("RGB", img.size, bg_color)

    # 将原图片粘贴到指定颜色背景上,并使用透明度作为掩码
    background.paste(img, (0, 0), img)

    # 保存处理后的图片
    background.save(output_image_path)

# 示例调用
convert_transparent_to_color_pil('input_image.png', 'output_image_pil.png', bg_color=(0, 128, 255))

详细解释

1.OpenCV方法函数封装

2.PIL方法函数封装

这两种方法都可以将透明背景转换为任意颜色背景,并支持在任意颜色背景之间进行转换。可以根据具体需求选择合适的工具和方法。

使用OpenCV将图片透明背景添加稍微大一点的白色背景

import cv2
import numpy as np

def add_white_background_with_padding_opencv(input_image_path, output_image_path, padding=10):
    """
    将透明背景的图片转换为带有稍微大一点的白色背景的图片,使用OpenCV实现。

    参数:
    input_image_path: str,输入图片的路径
    output_image_path: str,输出图片的路径
    padding: int,背景的扩展大小(默认为10像素)

    返回:
    无
    """
    # 读取带透明背景的图片(假设图片是PNG格式)
    img = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)

    # 检查是否读取成功
    if img is None:
        raise ValueError(f"Image at path {input_image_path} could not be read.")

    # 分离RGBA通道
    b, g, r, a = cv2.split(img)

    # 获取原图片的尺寸
    height, width = a.shape

    # 创建一个稍微大一点的白色背景
    new_height = height + 2 * padding
    new_width = width + 2 * padding
    white_background = np.ones((new_height, new_width, 3), dtype=np.uint8) * 255

    # 将Alpha通道归一化到0-1范围
    a = a / 255.0

    # 创建一个新的RGBA图像并将原图像放到中央
    result = np.zeros((new_height, new_width, 3), dtype=np.uint8)
    for c in range(3):
        result[padding:padding + height, padding:padding + width, c] = img[:, :, c] * a + white_background[padding:padding + height, padding:padding + width, c] * (1 - a)

    # 保存处理后的图片
    cv2.imwrite(output_image_path, result)

# 示例调用
add_white_background_with_padding_opencv('input_image.png', 'output_image_with_padding.png', padding=20)

详细解释

保存处理后的图片:将处理后的图片保存到指定路径。

通过这种方法,可以将带透明背景的图片转换为带有稍微大一点白色背景的图片。

以上就是python将图片透明背景转为白色背景的两种方法的详细内容,更多关于python图片背景转换的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文