当前位置: 首页 > 后端技术 > Python

Python实现照片转动画模式

时间:2023-03-25 20:44:57 Python

为了快速实现我们的目标,我们不自己编写图像处理程序,直接调用百度AI开放平台提供的接口来实现我们的需求。Coding这次我们导入下面两个库#-*-coding:utf-8-*-author:菜鸟小白的学习分享importrequests,base64我们需要对百度AI开放平台的接口进行认证,代码如下:#-*-coding:utf-8-*-作者:菜鸟小白的学习分享#百度AI开放平台认证函数defget_access_token():url='https://aip.baidubce.com/oaut...'data={'grant_type':'client_credentials',#固定值'client_id':'A3ppUrgl6H********NjDN4Bb',#APIKey'client_secret':'SqaeFpiPPC**********H1lsb0xO3w'#构建应用的SecretKey}res=requests.post(url,data=data)res=res.json()access_token=res['access_token']returnaccess_token因为百度AI平台提供了多种图片处理方式实现.请求URL的主体是一样的,但是参数不同,所以我们需要针对不同的处理方式来处理参数。代码如下:外汇红利活动https://www.fx61.com/activities#-*-编码:utf-8-*-作者:菜鸟小白的学习分享defget_config():img_before=input("请输入当前文件夹中要处理的图片名称:")process_action=['','selfie_anime','colourize','style_trans']print("支持以下处理动作:\n1:人像动画\n2:Coloringimages\n3:Stylizingimages")#处理动作:selfie_anime为人像动画,colourize为图像着色,style_trans为图像风格化i=int(input("请输入需要处理的动作:"))""“卡通:卡片generalpaintingstylepencil:铅笔风格color_pencil:彩色铅笔绘画风格warm:彩色糖果油画风格wave:神奈川冲浪的油画风格lavender:薰衣草油画风格mononoke:奇异油画风格scream:尖叫油画风格gothic:哥特式油画风格"""others=['','cartoon','pencil','color_pencil','warm','wave','lavender','mononoke','scream','gothic']j=0ifprocess_action[i]=='style_trans':print("支持转换的样式有:\n\1:卡通风格\n\2:铅笔风格\n\3:彩色铅笔风格\n\4:彩色糖果油画风格\n\5:神奈川海浪油画风格\n\6:薰衣草油画风格\n\7:诡异油画风格\n\8:尖叫油画风格\n\9:哥特式油画风格\n")j=int(input("请输入需要转换的样式类型(编号):"))returnimg_before,process_action[i],others[j]我们得到图像和处理参数后,使用此信息ontorequesttheBaiduAIOpenPlatform#-*-coding:utf-8-*-author:菜鸟小白的学习分享defimage_process(img_before,img_after,how_to_deal,others):#函数的三个参数,一个是文件转换前的名称,一个是转换后的文件名文件名,都在同一个目录下,第三个是图片处理能力选择request_url='https://aip.baidubce.com/rest...'+how_to_dealfile=open(img_before,'rb')#二进制读取图像origin_img=base64.b64encode(file.read())#Base64编码图像headers={'Content-Type':'application/x-www-form-urlencoded'}data={'access_token':get_access_token(),'image':origin_img,'option':others}res=requests.post(request_url,data=data,headers=headers)res=res.json()ifres:f=open(img_after,'wb')after_img=res['image']after_img=base64.b64decode(after_img)f.write(after_img)f.close()最后再写一次main函数调用#-*-coding:utf-8-*-author:if__name__=='__main__':#选择输入信息img_before,process_action,others=get_config()img_after=img_before.split('.')#将原始文件名分成列表img_after=img_after[0]+'_1.'+img_after[1]#新建文件名是原文件名加上_1image_process(img_before,img_after,process_action,others)print('done!')