百度智能云-人脸融合

最近做的一个Tkinter和人脸融合相结合的项目,用了双层的tk窗口,人脸融合的部分用的是百度智能云的接口,可以自行去注册接口参数,这里就不提供了。

直接上源码:

import tkinter

from tkinter import filedialog
from PIL import Image, ImageTk
from fuse import face_fuse


def get_pic1(): # 选择图片1
    global path1
    path1 = filedialog.askopenfilename()
    img = Image.open(path1).resize((400, 400))
    img = ImageTk.PhotoImage(img)
    lab1.img = img
    lab1.configure(image=img)


def get_pic2(): # 选择图片2
    global path2
    path2 = filedialog.askopenfilename()
    img = Image.open(path2).resize((400, 400))
    img = ImageTk.PhotoImage(img)
    lab2.img = img
    lab2.configure(image=img)


def face_page(): 
    # 创建二级界面
    page = tkinter.Toplevel()
    page.geometry("420x420")
    page.title("人脸融合")
    # 融合窗口
    lab = tkinter.Label(page, relief="groove")
    lab.place(x=10, y=10, width=400, height=400)
    # 开始融合
    face_fuse(path1, path2)
    # 展示图片
    img = Image.open('new.png').resize((400, 400))
    img = ImageTk.PhotoImage(img)
    lab.image = img
    lab.configure(image=img)


window = tkinter.Tk()
window.geometry("830x500")
window.title("人脸融合")

# 展示图片标签1
lab1 = tkinter.Label(window, relief="groove")
lab1.place(x=10, y=10, width=400, height=400)

# 展示图片标签2
lab2 = tkinter.Label(window, relief="groove")
lab2.place(x=420, y=10, width=400, height=400)

# 选择图片按钮1
btn1 = tkinter.Button(window, text="选择图片1", font=("微软雅黑", 16), command=get_pic1)
btn1.place(x=110, y=420, width=200, height=60)

# 选择图片按钮2
btn2 = tkinter.Button(window, text="选择图片2", font=("微软雅黑", 16), command=get_pic2)
btn2.place(x=520, y=420, width=200, height=60)

# 开始融合按钮
btn = tkinter.Button(window, text="开始融合", font=("微软雅黑", 16), command=face_page)
btn.place(x=365, y=420, width=100, height=60)

window.mainloop()

fuse为本地文件,里面主要是人脸融合的代码。access_token需要自己去百度智能云注册应用获取。

import base64
import json

import requests


def face_base64(img):  # 获取图片的base64值
    f = open(img, 'rb')
    img_date = f.read()
    data = base64.b64encode(img_date)
    data = data.decode()
    return data


def face_fuse(face1, face2):  # 人脸融合
    request_url = "https://aip.baidubce.com/rest/2.0/face/v1/merge"

    params = {
        "image_template":
            {"image": face_base64(face1), "image_type": "BASE64"},
        "image_target":
            {"image": face_base64(face2), "image_type": "BASE64"}
    }
    params = json.dumps(params)
    access_token = '自行获取'
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/json'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        content = response.json()
        img = content["result"]["merge_image"]
        temp = base64.b64decode(img)
        with open('new.png', "wb") as f:
            f.write(temp)
            f.close()


测试之前一定要去获取token哦,这是接口的注意事项。

百度智能云-人脸融合_第1张图片

 

你可能感兴趣的:(python,人工智能)