栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

opencv-python透明图和纯白背景图互转

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

opencv-python透明图和纯白背景图互转

import numpy as np
import cv2

'''
    opencv-python:透明背景图和纯白背景图互转
'''


# 修改透明背景为白色背景图
def transparent2white(img):
    height, width, channel = img.shape
    for h in range(height):
        for w in range(width):
            color = img[h, w]
            if (color == np.array([0, 0, 0, 0])).all():
                img[h, w] = [255, 255, 255, 255]

    return img


# 修改纯白背景图为透明背景图
def white2transparent(img):
    height, width, channel = img.shape
    for h in range(height):
        for w in range(width):
            color = img[h, w]
            if (color == np.array([255, 255, 255, 255])).all():
                img[h, w] = [0, 0, 0, 0]
    return img


if __name__ == '__main__':
    transparent_path = r'transparent.png'

    # 一:透明背景图转白背景图
    transparent_img = cv2.imread(transparent_path, -1)
    # print(transparent_img.shape) #(796, 796, 4)
    white_img = transparent2white(transparent_img)
    cv2.imwrite('white.jpg', white_img)

    # 二:白背景图转透明背景图
    white_img = cv2.imread('white.jpg')
    # print(white_img.shape)  # (796, 796, 3)
    white_img = cv2.cvtColor(white_img, cv2.COLOR_BGR2BGRA)  # 转为4通道
    # print(white_img.shape) # (796, 796, 4)
    new_transparent = white2transparent(white_img)
    cv2.imwrite('new_transparent.png', new_transparent)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/744495.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号