最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python為人臉照片添加口罩實戰(zhàn)

 更新時間:2022年04月22日 14:11:43   作者:.別拖至春天.  
本文主要介紹了Python為人臉照片添加口罩實戰(zhàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

效果展示

請?zhí)砑訄D片描述

在這里插入圖片描述

請?zhí)砑訄D片描述

請?zhí)砑訄D片描述

數(shù)據(jù)集展示

數(shù)據(jù)集來源:使用了開源數(shù)據(jù)集FaceMask_CelebA

github地址:https://github.com/sevenHsu/FaceMask_CelebA.git

部分人臉數(shù)據(jù)集:

在這里插入圖片描述

口罩樣本數(shù)據(jù)集:

在這里插入圖片描述

為人臉照片添加口罩代碼

這部分有個庫face_recognition需要安裝,如果之前沒有用過的小伙伴可能得費點功夫。
Face Recognition 庫主要封裝了dlib這一 C++ 圖形庫,通過 Python 語言將它封裝為一個非常簡單就可以實現(xiàn)人臉識別的 API 庫,屏蔽了人臉識別的算法細節(jié),大大降低了人臉識別功能的開發(fā)難度。

請?zhí)砑訄D片描述

在這里插入圖片描述

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : 2014Vee
import os
import numpy as np
from PIL import Image, ImageFile

__version__ = '0.3.0'

IMAGE_DIR = os.path.dirname('E:/play/FaceMask_CelebA-master/facemask_image/')
WHITE_IMAGE_PATH = os.path.join(IMAGE_DIR, 'front_14.png')
BLUE_IMAGE_PATH = os.path.join(IMAGE_DIR, 'front_14.png')
SAVE_PATH = os.path.dirname('E:/play/FaceMask_CelebA-master/save/synthesis/')
SAVE_PATH2 = os.path.dirname('E:/play/FaceMask_CelebA-master/save/masks/')


class FaceMasker:
    KEY_FACIAL_FEATURES = ('nose_bridge', 'chin')

    def __init__(self, face_path, mask_path, white_mask_path, save_path, save_path2, model='hog'):
        self.face_path = face_path
        self.mask_path = mask_path
        self.save_path = save_path
        self.save_path2 = save_path2
        self.white_mask_path = white_mask_path
        self.model = model
        self._face_img: ImageFile = None
        self._black_face_img = None
        self._mask_img: ImageFile = None
        self._white_mask_img = None

    def mask(self):
        import face_recognition

        face_image_np = face_recognition.load_image_file(self.face_path)
        face_locations = face_recognition.face_locations(face_image_np, model=self.model)
        face_landmarks = face_recognition.face_landmarks(face_image_np, face_locations)
        self._face_img = Image.fromarray(face_image_np)
        self._mask_img = Image.open(self.mask_path)
        self._white_mask_img = Image.open(self.white_mask_path)
        self._black_face_img = Image.new('RGB', self._face_img.size, 0)

        found_face = False
        for face_landmark in face_landmarks:
            # check whether facial features meet requirement
            skip = False
            for facial_feature in self.KEY_FACIAL_FEATURES:
                if facial_feature not in face_landmark:
                    skip = True
                    break
            if skip:
                continue

            # mask face
            found_face = True
            self._mask_face(face_landmark)

        if found_face:
            # save
            self._save()
        else:
            print('Found no face.')

    def _mask_face(self, face_landmark: dict):
        nose_bridge = face_landmark['nose_bridge']
        nose_point = nose_bridge[len(nose_bridge) * 1 // 4]
        nose_v = np.array(nose_point)

        chin = face_landmark['chin']
        chin_len = len(chin)
        chin_bottom_point = chin[chin_len // 2]
        chin_bottom_v = np.array(chin_bottom_point)
        chin_left_point = chin[chin_len // 8]
        chin_right_point = chin[chin_len * 7 // 8]

        # split mask and resize
        width = self._mask_img.width
        height = self._mask_img.height
        width_ratio = 1.2
        new_height = int(np.linalg.norm(nose_v - chin_bottom_v))

        # left
        mask_left_img = self._mask_img.crop((0, 0, width // 2, height))
        mask_left_width = self.get_distance_from_point_to_line(chin_left_point, nose_point, chin_bottom_point)
        mask_left_width = int(mask_left_width * width_ratio)
        mask_left_img = mask_left_img.resize((mask_left_width, new_height))

        # right
        mask_right_img = self._mask_img.crop((width // 2, 0, width, height))
        mask_right_width = self.get_distance_from_point_to_line(chin_right_point, nose_point, chin_bottom_point)
        mask_right_width = int(mask_right_width * width_ratio)
        mask_right_img = mask_right_img.resize((mask_right_width, new_height))

        # merge mask
        size = (mask_left_img.width + mask_right_img.width, new_height)
        mask_img = Image.new('RGBA', size)
        mask_img.paste(mask_left_img, (0, 0), mask_left_img)
        mask_img.paste(mask_right_img, (mask_left_img.width, 0), mask_right_img)

        # rotate mask
        angle = np.arctan2(chin_bottom_point[1] - nose_point[1], chin_bottom_point[0] - nose_point[0])
        rotated_mask_img = mask_img.rotate(angle, expand=True)

        # calculate mask location
        center_x = (nose_point[0] + chin_bottom_point[0]) // 2
        center_y = (nose_point[1] + chin_bottom_point[1]) // 2

        offset = mask_img.width // 2 - mask_left_img.width
        radian = angle * np.pi / 180
        box_x = center_x + int(offset * np.cos(radian)) - rotated_mask_img.width // 2
        box_y = center_y + int(offset * np.sin(radian)) - rotated_mask_img.height // 2

        # add mask
        self._face_img.paste(mask_img, (box_x, box_y), mask_img)

        # split mask and resize
        width = self._white_mask_img.width
        height = self._white_mask_img.height
        width_ratio = 1.2
        new_height = int(np.linalg.norm(nose_v - chin_bottom_v))

        # left
        mask_left_img = self._white_mask_img.crop((0, 0, width // 2, height))
        mask_left_width = self.get_distance_from_point_to_line(chin_left_point, nose_point, chin_bottom_point)
        mask_left_width = int(mask_left_width * width_ratio)
        mask_left_img = mask_left_img.resize((mask_left_width, new_height))

        # right
        mask_right_img = self._white_mask_img.crop((width // 2, 0, width, height))
        mask_right_width = self.get_distance_from_point_to_line(chin_right_point, nose_point, chin_bottom_point)
        mask_right_width = int(mask_right_width * width_ratio)
        mask_right_img = mask_right_img.resize((mask_right_width, new_height))

        # merge mask
        size = (mask_left_img.width + mask_right_img.width, new_height)
        mask_img = Image.new('RGBA', size)
        mask_img.paste(mask_left_img, (0, 0), mask_left_img)
        mask_img.paste(mask_right_img, (mask_left_img.width, 0), mask_right_img)

        # rotate mask
        angle = np.arctan2(chin_bottom_point[1] - nose_point[1], chin_bottom_point[0] - nose_point[0])
        rotated_mask_img = mask_img.rotate(angle, expand=True)

        # calculate mask location
        center_x = (nose_point[0] + chin_bottom_point[0]) // 2
        center_y = (nose_point[1] + chin_bottom_point[1]) // 2

        offset = mask_img.width // 2 - mask_left_img.width
        radian = angle * np.pi / 180
        box_x = center_x + int(offset * np.cos(radian)) - rotated_mask_img.width // 2
        box_y = center_y + int(offset * np.sin(radian)) - rotated_mask_img.height // 2

        # add mask
        self._black_face_img.paste(mask_img, (box_x, box_y), mask_img)

    def _save(self):
        path_splits = os.path.splitext(self.face_path)
        # new_face_path = self.save_path + '/' + os.path.basename(self.face_path) + '-with-mask' + path_splits[1]
        # new_face_path2 = self.save_path2 + '/' + os.path.basename(self.face_path) + '-binary' + path_splits[1]
        new_face_path = self.save_path + '/' + os.path.basename(self.face_path) + '-with-mask' + path_splits[1]
        new_face_path2 = self.save_path2 + '/'  + os.path.basename(self.face_path) + '-binary' + path_splits[1]
        self._face_img.save(new_face_path)
        self._black_face_img.save(new_face_path2)

    #         print(f'Save to {new_face_path}')

    @staticmethod
    def get_distance_from_point_to_line(point, line_point1, line_point2):
        distance = np.abs((line_point2[1] - line_point1[1]) * point[0] +
                          (line_point1[0] - line_point2[0]) * point[1] +
                          (line_point2[0] - line_point1[0]) * line_point1[1] +
                          (line_point1[1] - line_point2[1]) * line_point1[0]) / \
                   np.sqrt((line_point2[1] - line_point1[1]) * (line_point2[1] - line_point1[1]) +
                           (line_point1[0] - line_point2[0]) * (line_point1[0] - line_point2[0]))
        return int(distance)

    # FaceMasker("/home/aistudio/data/人臉.png", WHITE_IMAGE_PATH, True, 'hog').mask()


from pathlib import Path

images = Path("E:/play/FaceMask_CelebA-master/bbox_align_celeba").glob("*")
cnt = 0
for image in images:
    if cnt < 1:
        cnt += 1
        continue
    FaceMasker(image, BLUE_IMAGE_PATH, WHITE_IMAGE_PATH, SAVE_PATH, SAVE_PATH2, 'hog').mask()
    cnt += 1
    print(f"正在處理第{cnt}張圖片,還有{99 - cnt}張圖片")

掩膜生成代碼

這部分其實就是對使用的口罩樣本的二值化,因為后續(xù)要相關模型會用到

請?zhí)砑訄D片描述

請?zhí)砑訄D片描述

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是存放待轉(zhuǎn)換圖片的目錄
    destsoure是存在輸出轉(zhuǎn)換后圖片的目錄
    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():
    # 切換到源目錄,遍歷源目錄下所有圖片
    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()

到此這篇關于Python為人臉照片添加口罩實戰(zhàn)的文章就介紹到這了,更多相關Python人臉照片添加口罩內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python中類的創(chuàng)建和實例化操作示例

    Python中類的創(chuàng)建和實例化操作示例

    這篇文章主要介紹了Python中類的創(chuàng)建和實例化操作,涉及Python面向?qū)ο蟪绦蛟O計中類的定義、實例化、方法調(diào)用等相關操作技巧,需要的朋友可以參考下
    2019-02-02
  • 詳解python函數(shù)傳參傳遞dict/list/set等類型的問題

    詳解python函數(shù)傳參傳遞dict/list/set等類型的問題

    這篇文章主要介紹了詳解python函數(shù)傳參傳遞dict/list/set等類型的問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • Matplotlib使用字符串代替變量繪制散點圖的方法

    Matplotlib使用字符串代替變量繪制散點圖的方法

    這篇文章主要介紹了Matplotlib使用字符串代替變量繪制散點圖的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-02-02
  • Python通過yagmail實現(xiàn)發(fā)送郵件代碼解析

    Python通過yagmail實現(xiàn)發(fā)送郵件代碼解析

    這篇文章主要介紹了Python通過yagmail實現(xiàn)發(fā)送郵件代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-10-10
  • 使用python opencv對目錄下圖片進行去重的方法

    使用python opencv對目錄下圖片進行去重的方法

    今天小編就為大家分享一篇使用python opencv對目錄下圖片進行去重的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • 多版本python的pip 升級后, pip2 pip3 與python版本失配解決方法

    多版本python的pip 升級后, pip2 pip3 與python版本失配解決方法

    在本篇文章里小編給大家整理的是關于多版本python的pip 升級后, pip2 pip3 與python版本失配的解決方法內(nèi)容,需要的朋友們學習下。
    2019-09-09
  • Python中optionParser模塊的使用方法實例教程

    Python中optionParser模塊的使用方法實例教程

    這篇文章主要介紹了Python中optionParser模塊的使用方法,功能非常強大,需要的朋友可以參考下
    2014-08-08
  • 利用Python微信群發(fā)英語每日一句

    利用Python微信群發(fā)英語每日一句

    這篇文章主要為大家詳細介紹了Python如何利用wxauto實現(xiàn)微信群發(fā)消息,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-11-11
  • Python pymysql操作MySQL詳細

    Python pymysql操作MySQL詳細

    pymysql是Python3.x中操作MySQL數(shù)據(jù)庫的模塊,其兼容于MySQLdb,使用方法也與MySQLdb幾乎相同,但是性能不如MySQLdb,但是由于其安裝使用方便、對中文兼容性也更好等優(yōu)點,被廣泛使用??梢允褂胮ip install pymysql進行安裝。
    2021-09-09
  • python實現(xiàn)一個猜拳游戲

    python實現(xiàn)一個猜拳游戲

    這篇文章主要為大家詳細介紹了python實現(xiàn)一個猜拳游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-04-04

最新評論

苏尼特右旗| 布拖县| 霸州市| 文登市| 绥宁县| 桐柏县| 商河县| 闸北区| 内乡县| 伊金霍洛旗| 泸水县| 通城县| 遵义市| 长沙市| 鸡泽县| 阿瓦提县| 金塔县| 肇源县| 景泰县| 炉霍县| 工布江达县| 宾川县| 含山县| 嘉义县| 威海市| 神木县| 滨州市| 富平县| 登封市| 高尔夫| 嘉黎县| 临江市| 永康市| 五大连池市| 荆门市| 岗巴县| 铁力市| 宜城市| 合川市| 长子县| 屯昌县|