Python图片掩膜的实现

import re
import os
import PIL.Image as Image


# 获取文件地址(返回为列表形式)
#            路径 文件关键字
def getfiles(path, keys):
    names = []
    for dirpath, dirname, filenames in os.walk(path):
        for filepath in filenames:
            image_name = os.path.join(dirpath, filepath)
            str1 = re.compile(keys)
            match_obj = str1.findall(image_name)
            if match_obj:
                names.append(image_name)
    return names


# 掩膜
# 返回一个字典
#            文件路径 处理数量 像素点     
def file_mask(path, number, pixel):
    dict1 = {}
    for imgf in range(number // 2):  # 这是因为我把掩膜图和原图放在了一个文件夹中
        imgfile = getfiles(path, '[^mask].png')[imgf]
        img = Image.open(imgfile)
        img = img.convert('RGBA')
        w1 = img.width  # 获取图片的宽度
        h1 = img.height  # 获取图片的高度
        maskfile = getfiles(path, 'mask')[imgf]
        mask = Image.open(maskfile)
        mask = mask.convert('RGBA')

        for h in range(h1):
            for w in range(w1):
                if mask.getpixel((w, h)) == pixel:
                    img.putpixel((w, h), (255, 255, 255, 0))  # 0表示不透明度

        savepath = os.path.join(path, imgfile)  # 连接路径
        img.save(savepath)  # 保存
        dict1[imgf] = imgfile
    return dict1

你可能感兴趣的:(python,开发语言,pygame)