AI換臉


AI換臉

技術

調用到百度的AI接口,layui的圖片上傳,柵格化布局

核心代碼

純py文件運行

 # 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(name, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        base64_code = base64_data.decode()
    return base64_code


# 調用百度的接口,實現融合圖片
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": "NONE"
        },
        "image_target": {
            "image": target,
            "image_type": "BASE64",
            "quality_control": "NONE"
        },
        "merge_degree": "NORMAL"
    }
    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__':
    template = read_photo('img/jjy.jpg')
    target = read_photo('img/mzc.jpeg')
    token = get_token('你的ID', '你的key')
    face_fusion(token, template, target)

實戰開發-換臉大法

操作步驟

1.准備頁面:兩個圖片上傳,一個為模板圖,一個為目標圖,還有一個結果圖

2.上傳照片后,當點擊“開始換臉”就會將兩張圖片的地址發送到后端,通過上面的純py代碼,下載換臉后的照片到本地,將地址返還給前端

3.前端將src進行更換即可

展示

將知否中的盛明蘭與張一凡進行換臉

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM