Python實戰——為人臉照片新增口罩

專注的阿熊發表於2022-05-19

import os

from PIL import Image

# 源目錄

# MyPath = 'E:/play/FaceMask_CelebA-master/facemask_image/'

MyPath = 'E:/play/FaceMask_CelebA-master/save/masks/'

# 輸出目錄

OutPath = 'E:/play/FaceMask_CelebA-master/save/Binarization/'

def processImage(filesoure, destsoure, name, imgtype):

     '''

     filesoure 是存放待轉換圖片的目錄

     destsoure 是存在輸出轉換後圖片的目錄

     name 是檔名

     imgtype 是檔案型別

     '''

     imgtype = 'bmp' if imgtype == '.bmp' else 'png'

     # 開啟圖片

     im = Image.open(filesoure + name)

     # =============================================================================

     #     # 縮放比例

     #     rate =max(im.size[0]/640.0 if im.size[0] > 60 else 0, im.size[1]/1136.0 if im.size[1] > 1136 else 0)

     #     if rate:

     #         im.thumbnail((im.size[0]/rate, im.size[1]/rate))

     # =============================================================================

     img = im.convert("RGBA")

     pixdata = img.load()

     # 二值化

     for y in range(img.size[1]):

         for x in range(img.size[0]):

             if pixdata[x, y][0] < 90:

                 pixdata[x, y] = (0, 0, 0, 255)

     for y in range(img.size[1]):

         for x in range(img.size[0]):

             if pixdata[x, y][1] < 136:

                 pixdata[x, y] = (0, 0, 0, 255)

     for y in range(img.size[1]):

         for x in range(img.size[0]):

             if pixdata[x, y][2] > 0:

                 pixdata[x, y] = (255, 255, 255, 255)

     img.save(destsoure + name, imgtype)

def run():

     # 切換到源目錄,跟單網gendan5.com遍歷源目錄下所有圖片

     os.chdir(MyPath)

     for i in os.listdir(os.getcwd()):

         # 檢查字尾

         postfix = os.path.splitext(i)[1]

         name = os.path.splitext(i)[0]

         name2 = name.split('.')

         if name2[1] == 'jpg-binary' or name2[1] == 'png-binary':

             processImage(MyPath, OutPath, i, postfix)

if __name__ == '__main__':

     run()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2895290/,如需轉載,請註明出處,否則將追究法律責任。

相關文章