去除白色背景_pygame实现

2024-05-07

使用pygame实现去除白色背景,将其变为透明 ```python

import optparse
import pygame
Usage = "图片转换为透明格式"
Parser = optparse.OptionParser(usage=Usage)
def main(args):
    pygame.init()
    size = 1, 1
    pygame.display.set_mode(size)
    img_sur = pygame.image.load(args[0]).convert_alpha()
    with pygame.PixelArray(img_sur) as pixel:
        # BG_color = pygame.Surface.get_at((1, 1))
        for alpha in range(256):
            pixel.replace((255, 255, 255, 255), (255, 255, 255, 0))#将所有白色改为透明
        sur = pixel.make_surface()
    pygame.image.save(sur, args[1])
    pygame.quit()
    exit()
if __name__ == '__main__':
    *_, args = Parser.parse_args()
    if len(args) < 2:
        raise("请输入原图片文件名和目标文件名!")
    main(args)