Spaces:
Paused
Paused
import gradio as gr | |
import requests | |
import base64 | |
import cv2 | |
import json | |
import numpy as np | |
# token获取 | |
def get_token(client_id, client_secret): | |
# client_id为官网获取的API Key,client_secret为官网获取的Secret Key.下行client_id=后的马赛克为你的API Key,client_secret=后的马赛克为你的Secret Key | |
url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}" # 注意此处的&符号 | |
response = requests.get(url) | |
resultJson = response.json() | |
return resultJson['access_token'] | |
def face_merge(image_template,image_target): | |
success,encode_image_temp = cv2.imencode(".jpg",image_template) #注意这句编码,否则图像质量不合格 | |
image_temp = encode_image_temp.tobytes() | |
image_temp = base64.b64encode(image_temp) | |
success,encode_image_targ = cv2.imencode(".jpg",image_target) #注意这句编码,否则图像质量不合格 | |
image_targ = encode_image_targ.tobytes() | |
image_targ = base64.b64encode(image_targ) | |
request_url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge' | |
params = { | |
"image_template": { # 将其中一张图片设置为模板(相当于底层图片) | |
"image": str(image_temp,'utf-8'), | |
"image_type": "BASE64", | |
"quality_control": "NORMAL" | |
}, | |
"image_target": { # 将其中一张图片设置为目标(相当于人脸信息“叠加”到模板上) | |
"image": str(image_targ,'utf-8'), | |
"image_type": "BASE64", | |
"quality_control": "NORMAL" | |
}, | |
"merge_degree": "HIGH", # 融合程度 | |
"position": 2, #左上角水印 | |
"language": 1, #英语水印 | |
} | |
params=json.dumps(params) | |
access_token = get_token('gZBF8TaiLfewLu4XdWIVe5H1', 'O7zkY3cc1OYu2GHwqvsyxI4YaCgdRn7A') | |
request_url = request_url + "?access_token=" + access_token | |
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"] | |
res = base64.b64decode(res) | |
nparr = np.frombuffer(res,np.uint8) | |
img_np = cv2.imdecode(nparr,cv2.IMREAD_COLOR) | |
return img_np | |
else: | |
print(str(result['error_code']) + result['error_msg']) | |
return result['error_code'] | |
with gr.Blocks() as demo: | |
gr.Markdown("Face merge.") | |
with gr.Row(): | |
image_template = gr.Image() | |
image_target = gr.Image() | |
image_output = gr.Image() | |
image_button = gr.Button("Merge") | |
image_button.click(face_merge, inputs=[image_template,image_target], outputs=image_output) | |
gr.close_all() | |
demo.launch() |