基于百度云人脸融合API的python实现视频人像换脸

import os
import cv2
import re
import base64
import requests 

AK = 0        #输入你的AK
SK = 0        #输入你的SK
inPath = 0      #输入你分裂视频的图片路劲
aimPath = 0     #输入你想换脸的图像的路劲
outPath = 0     #输入你换完脸图像的保存路径
videoPath = 0   #输入原视频路径
savePath = 0    #输入你想保存结果的路劲和文件名

sum = 1
def resquest(AK,SK):
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+AK+'&client_secret='+SK
    response = requests.get(host)
    if response:
        return response.json()['result']

def splitmv(videoPath, svPath):
    cap = cv2.VideoCapture(videoPath)
    numFrame = 0
    while True:
        if cap.grab():
            flag, frame = cap.retrieve()
            if not flag:
                continue
            else:
                #cv2.imshow('video', frame)
                numFrame += 1
                newPath = svPath + str(numFrame) + ".jpg"
                cv2.imencode('.jpg', frame)[1].tofile(newPath)
        if cv2.waitKey(10) == 27:
            break

def faceex(inpath,aimpath,outpath):
    sum = 1           #换的图像的第一张,建议以顺序命名
    while sum < 2140:  #最后一张
        f1=open(inpath,'rb') #二进制方式打开图文件
        ls_f1=base64.b64encode(f1.read()) #读取文件内容,转换为base64编码
        f1.close()
        str1 = str(ls_f1, encoding="utf-8")
        
        f2=open(aimpath,'rb') #二进制方式打开图文件
        ls_f2=base64.b64encode(f2.read()) #读取文件内容,转换为base64编码
        f2.close()
        str2 = str(ls_f2, encoding="utf-8")
        
        request_url = "https://aip.baidubce.com/rest/2.0/face/v1/merge"
        
        params = "{\"image_template\":{\"image\":\""+str1+"\",\"image_type\":\"BASE64\",\"quality_control\":\"NONE\"},\"image_target\":{\"image\":\""+str2+"\",\"image_type\":\"BASE64\",\"quality_control\":\"NONE\"}}"
        access_token = resquest(AK,SK)
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            print (response.json())
        
        re1 = response.json() 
        print(type(re1))
        print(re1['result'])
        re = re1['result']['merge_image']
        print(re)
        
        image_data = base64.b64decode(re)
        with open(outpath, 'wb') as f:
            f.write(image_data)
        sum = sum+1
        print(sum)

def get_images(inpath):
    file_list = []
    for root, dirs, files in os.walk(inpath):
        if not files:
            continue
        for file in files:
            if file.endswith('.jpg'):
                file_list.append(os.path.join(root, file))
                #file_list.append(file)
    return file_list
 
def key_sort(image_path):
    pattern = re.compile("\d+")
    image_name = os.path.basename(image_path)
    return int(pattern.findall(image_name)[0])

def main():
    path = videoPath
    file_list = get_images(path)
    file_list.sort(key=key_sort)
    fps = 30
    img_size = (720, 1280) 
    save_path = savePath
    fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
    video_writer = cv2.VideoWriter(save_path, fourcc, fps, img_size)
    for file_name in file_list:
        print(file_name)
        img = cv2.imread(file_name)
        video_writer.write(img)
 
    video_writer.release()
 
if __name__ == "__main__":
    splitmv(videoPath, inPath)   #输入分裂的视频路劲和保存的地址
    faceex(inPath,aimPath,outPath)
    main()

 

有问题可以练习QQ1498356982

你可能感兴趣的:(python,opencv)