• python转换图片透明背景为白色


    两种方法,思路一致:

    法一:

    import cv2
    
    # 修改透明背景为白色
    def transparence2white(img):
        sp=img.shape  # 获取图片维度
        width=sp[0]  # 宽度
        height=sp[1]  # 高度
        for yh in range(height):
            for xw in range(width):
                color_d=img[xw,yh]  # 遍历图像每一个点,获取到每个点4通道的颜色数据
                if(color_d[3]==0):  # 最后一个通道为透明度,如果其值为0,即图像是透明
                    img[xw,yh]=[255,255,255,255]  # 则将当前点的颜色设置为白色,且图像设置为不透明
        return img
    
    img=cv2.imread('bar.png',-1)  # 读取图片。-1将图片透明度传入,数据由RGB的3通道变成4通道
    img=transparence2white(img)  # 将图片传入,改变背景色后,返回
    cv2.imwrite('bar.png',img)  # 保存图片,文件名自定义,也可以覆盖原文件

    法二:

    from PIL import Image
     
    def transparence2white(img):
    #     img=img.convert('RGBA')  # 此步骤是将图像转为灰度(RGBA表示4x8位像素,带透明度掩模的真彩色;CMYK为4x8位像素,分色等),可以省略
        sp=img.size
        width=sp[0]
        height=sp[1]
        print(sp)
        for yh in range(height):
            for xw in range(width):
                dot=(xw,yh)
                color_d=img.getpixel(dot)  # 与cv2不同的是,这里需要用getpixel方法来获取维度数据
                if(color_d[3]==0):
                    color_d=(255,255,255,255)
                    img.putpixel(dot,color_d)  # 赋值的方法是通过putpixel
        return img
     
    
    img=Image.open('bar.png')
    img=transparence2white(img)
    # img.show()  # 显示图片
    img.save('bar3.png')  # 保存图片
  • 相关阅读:
    DHT(Distributed Hash Table) Translator
    Introducing shard translator
    【转】shell脚本中echo显示内容带颜色
    javac 错误: 编码GBK的不可映射字符
    一致性哈希(consistent hashing)
    在bash shell中使用getfattr查看文件扩展属性
    css3在不同型号手机浏览器上的兼容一览表
    META是什么意思?
    JS异步加载的三种方式
    AJAX中的同步加载与异步加载
  • 原文地址:https://www.cnblogs.com/jaysonteng/p/12793178.html
Copyright © 2020-2023  润新知