使用Python快速實現人臉融合

你是否會好奇自己的孩子將來會長什麼樣子,或者純粹想YY一下自己和某某人在一起的話,孩子會是什麼樣的,那就來試試吧。

前期準備

預測是通過人臉融合技術實現的,需要藉助 Python 和百度現有的 API 。

(1)註冊百度賬號

1.首先登陸 百度智能雲 ,沒有賬號的可以註冊一下。
在這裏插入圖片描述

2.點擊:產品服務 -> 人工智能 -> 人臉識別,進入人臉識別產品菜單。
在這裏插入圖片描述
3.點擊創建應用創建自己的應用,創建成功後會生成自己的 API Key 和 Secret Key 一會會用到。
在這裏插入圖片描述

(2)準備Python環境

1.此接口可以使用多種方法調用,因爲 Python 的便捷性,本文使用 Python 語言來演示。其他語言的操作可以參考官方API
在這裏插入圖片描述
2.Python 的安裝十分簡單和快捷,不明白的可以參考以下博文。

《Python基礎:安裝 Python》

(3)準備照片

1.測試需要準備男女的照片,經過測試,最好證明照片,證件照最優,合成效果最好。我試了一些非正面照片,那合成結果真是慘不忍睹。
2.調用接口時,需要男女各一張,可以分別命名爲 boy 和 girl 。圖片參數現支持PNG、JPG、JPEG、BMP,不支持GIF圖片。

實現思路

(1)獲取本地照片,並轉換成base64

# 根據圖片名讀取圖片,並轉換成base64
def read_photo(name):
    with open('./%s' % name, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        s = base64_data.decode()
        return s

(2)獲取token

# 獲取token
# client_id 爲官網獲取的 API Key , client_secret 爲官網獲取的 Secret Key
def get_token(client_id, client_secret):
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
    params = {"client_id": client_id, "client_secret": client_secret}
    response = requests.get(url, params=params)
    resultJson = response.json()
    return resultJson['access_token']

(3)調用人臉融合接口

# 調用百度的接口,實現融合圖片
def face_fusion(token, template, target):
    url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge'
    request_url = url + '?access_token=' + token
    params = {
        "image_template": {
            "image": template,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "image_target": {
            "image": target,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "merge_degree": "HIGH"
    }
    params = json.dumps(params)
    headers = {'content-type': 'application/json'}
    result = requests.post(request_url, data=params, headers=headers).json()
    if result['error_code'] == 0:
        res = result["result"]["merge_image"]
        down_photo(res)
    else:
        print(str(result['error_code'])+result['error_msg'])

(4)保存融合結果

# 下載融合後圖片,保存成名爲 result.jpg 的文件
def down_photo(data):
    imagedata = base64.b64decode(data)
    file = open('./result.jpg', "wb")
    file.write(imagedata)

編碼實現

完整的代碼需要引入一些 Python 模塊,如果沒有的需要安裝,比如:requests。安裝也比較簡單,直接使用 pip 安裝。

# 安裝requests
pip install requests

# 可能因爲pip的問題安裝失敗,可以執行以下命令解決
python -m pip install --upgrade pip 

完整代碼

 # encoding:utf-8
import requests 
import base64
import json

# 獲取token
# client_id 爲官網獲取的AK, client_secret 爲官網獲取的SK
def get_token(client_id, client_secret):
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
    params = {"client_id": client_id, "client_secret": client_secret}
    response = requests.get(url, params=params)
    resultJson = response.json()
    return resultJson['access_token']

# 根據圖片名讀取圖片,並轉換成base64
def read_photo(name):
    with open('./%s' % name, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        bd = base64_data.decode()
        return bd


# 調用百度的接口,實現融合圖片
def face_fusion(token, template, target):
    url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge'
    request_url = url + '?access_token=' + token
    params = {
        "image_template": {
            "image": template,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "image_target": {
            "image": target,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "merge_degree": "HIGH"
    }
    params = json.dumps(params)
    headers = {'content-type': 'application/json'}
    result = requests.post(request_url, data=params, headers=headers).json()
    if result['error_code'] == 0:
        res = result["result"]["merge_image"]
        down_photo(res)
    else:
        print(str(result['error_code'])+result['error_msg'])

# 下載融合後圖片
def down_photo(data):
    imagedata = base64.b64decode(data)
    file = open('./result.jpg', "wb")
    file.write(imagedata)

# 主程序
if __name__ == '__main__':
	boy = read_photo('boy.jpg')
	girl = read_photo('girl.jpg')
	token = get_token('API Key', 'Secret Key')
	face_fusion(token, boy, girl)

默認是以男爲模板,可以修改爲以女爲模板

融合效果

1.融合前

在這裏插入圖片描述在這裏插入圖片描述

2.融合後

以男生爲模板
在這裏插入圖片描述
以女生爲模板,額~ 有點怪怪的。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章