当前位置:   article > 正文

头像动漫化——微信小程序+Flask后端调用AnimeGanV2_微信小程序3d卡通人物

微信小程序3d卡通人物

之前写了篇文章《超越前作,实现动漫风格迁移——AnimeGANv2》,里面提到使用AnimeGANv2实现人物动漫化,生成一个独一无二对自己价值珍贵的头像。不过操作起来有亿点点麻烦,所以希望做一个小程序,直接在手机端就能一键生成专属于自己的动漫头像,下面是展示效果!!!

一、核心功能设计

该小程序想要实现的是将微信头像或者选择相册中的照片动漫化,所以拆解需求后,整理的核心功能如下:

  1. 授权登录获取头像及昵称
  2. 选择相册中的图片
  3. 点击动漫化按钮,调用Flask后端生成图像
  4. 保存图像

二、微信小程序前端实现步骤

首先新建一个空白的微信小程序项目,详细步骤可以参考之前《Python+微信小程序开发(一)了解和环境搭建》的文章。

1.登录界面

在pages/index/index.wxml设计页面:

  1. <view wx:if="{{canIUse}}">
  2. <view class='header'>
  3. <view class="userinfo-avatar">
  4. <open-data type="userAvatarUrl"></open-data>
  5. </view>
  6. </view>
  7. <view class="content">
  8. <view>申请获取以下权限</view>
  9. <text>获得您的公开信息(昵称,头像等)</text>
  10. </view>
  11. <button wx:if="{{canIUse}}" class="loginBtn" type="primary" lang="zh_CN" bindtap="bindGetUserProfile" >
  12. 授权登录
  13. </button>
  14. </view>

在pages/index/index.js添加用户信息验证:

  1. bindGetUserProfile(e) //当用户点击授权登录按钮触发 bindGetUserInfo函数
  2. {
  3. var that=this
  4. wx.getUserProfile({
  5. desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
  6. success: (res) => {
  7. // console.log(res.userInfo)
  8. var avantarurl=res.userInfo.avatarUrl;
  9. wx.navigateTo({
  10. url: '../../pages/change/change?url='+ avantarurl ,
  11. })
  12. },
  13. fail:(res)=>{
  14. console.log(1)
  15. }
  16. })
  17. },

其中将头像的url传递给avanta界面。

效果如下:

  

2.avantar页面

在该页面进行选取照片以及头像动漫化。

在pages/avantar/avantar.wxml设计页面:

  1. <!--pages/avantar/avantar.wxml-->
  2. <view class='preview'>
  3. <view class="Imgtag">
  4. <image class="tag" src='{{prurl}}' mode='aspectFit'></image>
  5. </view>
  6. <view class="bottomAll">
  7. <button bindtap='selectImg' class="saveBtn">选择图片</button>
  8. <button bindtap='generateAvantar' class="saveBtn">动漫化</button>
  9. <button bindtap='save' class="saveBtn">保存头像</button>
  10. </view>
  11. </view>

在pages/avantar/avantar.js定义函数:

其中onload函数接收index传递的url。

  1. onLoad: function (options) {
  2. if(options.url){
  3. // console.log(options.url)
  4. var path = this.headimgHD(options.url)
  5. console.log(path)
  6. this.setData({
  7. image:path,
  8. // image1:path,
  9. // baseURL:path
  10. })
  11. }

 其中chooseImage函数实现选择图片。

  1. chooseImage() {
  2. var that = this;
  3. wx.showActionSheet({
  4. itemList: ['从相册中选择', '拍照'],
  5. itemColor: "#FAD143",
  6. success: function (res) {
  7. if (!res.cancel) {
  8. wx.showLoading({
  9. title: '正在读取...',
  10. })
  11. if (res.tapIndex == 0) {
  12. that.chooseWxImage1('album', 1)
  13. } else if (res.tapIndex == 1) {
  14. that.chooseWxImage1('camera', 1)
  15. }
  16. }
  17. }
  18. })
  19. },

savePic函数保存照片。

  1. savePic(e) {
  2. let that = this
  3. var baseImg = that.data.baseImg
  4. //保存图片
  5. var save = wx.getFileSystemManager();
  6. var number = Math.random();
  7. save.writeFile({
  8. filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
  9. data: baseImg,
  10. encoding: 'base64',
  11. success: res => {
  12. wx.saveImageToPhotosAlbum({
  13. filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
  14. success: function (res) {
  15. wx.showToast({
  16. title: '保存成功',
  17. })
  18. },
  19. fail: function (err) {
  20. console.log(err)
  21. }
  22. })
  23. console.log(res)
  24. },
  25. fail: err => {
  26. console.log(err)
  27. }
  28. })
  29. },

generateAvantar函数调用postdata函数实现头像动漫化。 

  1. generateAvantar:function(e){
  2. var that = this
  3. console.log(that.data.prurl)
  4. wx.uploadFile({
  5. url: 'http://127.0.0.1:8090/postdata',
  6. filePath: that.data.prurl,
  7. name: 'content',
  8. success: function (res) {
  9. console.log(res.data);
  10. var resurl=JSON.parse(res.data)['resurl']
  11. that.setData({
  12. prurl: resurl
  13. })
  14. if (res) {
  15. wx.showToast({
  16. title: '转换完成',
  17. duration: 3000
  18. });
  19. }
  20. },
  21. fail: (res) =>{
  22. console.log('fail===',res)
  23. }
  24. })
  25. },

三、Flask后端实现步骤

1.配置RESTful路由方法

  1. @app.route('/postdata', methods=['POST'])
  2. def postdata():
  3. f = request.files['content']
  4. print(f)
  5. user_input = request.form.get("name")
  6. basepath = os.path.dirname(__file__) # 当前文件所在路径
  7. src_imgname = str(uuid.uuid1()) + ".jpg"
  8. upload_path = os.path.join(basepath, 'static/srcImg/')
  9. if os.path.exists(upload_path)==False:
  10. os.makedirs(upload_path)
  11. f.save(upload_path + src_imgname)
  12. # img = cv2.imread(upload_path + src_imgname, 1)
  13. save_path = os.path.join(basepath, 'static/resImg/')
  14. if os.path.exists(save_path) == False:
  15. os.makedirs(save_path)
  16. generateAvantar(src_imgname,upload_path,save_path)
  17. resSets["value"] = 10
  18. resSets["resurl"] = "http://127.0.0.1:8090" +'/static/resImg/' + src_imgname
  19. return json.dumps(resSets, ensure_ascii=False)

该代码主要接受前端传来的图片url,进行处理并且通过json传回去。

2.调用AnimeGanv2实现动漫化

  1. net = Generator()
  2. net.load_state_dict(torch.load(args.checkpoint, map_location="cpu"))
  3. net.to(args.device).eval()
  4. # print(f"model loaded: {args.checkpoint}")
  5. # os.makedirs(args.output_dir, exist_ok=True)
  6. def load_image(image_path, x32=False):
  7. img = cv2.imread(image_path).astype(np.float32)
  8. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  9. h, w = img.shape[:2]
  10. if x32: # resize image to multiple of 32s
  11. def to_32s(x):
  12. return 256 if x < 256 else x - x%32
  13. img = cv2.resize(img, (to_32s(w), to_32s(h)))
  14. img = torch.from_numpy(img)
  15. img = img/127.5 - 1.0
  16. return img
  17. def generateAvantar(src_imgname,upload_path,save_path):
  18. image = load_image((upload_path+src_imgname), args.x32)
  19. with torch.no_grad():
  20. input = image.permute(2, 0, 1).unsqueeze(0).to(args.device)
  21. out = net(input, args.upsample_align).squeeze(0).permute(1, 2, 0).cpu().numpy()
  22. out = (out + 1)*127.5
  23. out = np.clip(out, 0, 255).astype(np.uint8)
  24. cv2.imwrite(os.path.join(save_path, src_imgname), cv2.cvtColor(out, cv2.COLOR_BGR2RGB))

该代码主要是调用AnimeGanv2实现图像动漫化。   

最后实现效果:

    

总结

其实这个小程序实现起来并不是很难,只需要配置基础的深度学习环境和Flask编程就好了,再了解一些小程序基本的api,就能够开发出来,大家有时间的可以去试试,后台我已经搭好了,大家可以直接使用,可以看看效果。有什么问题可以在评论区留言,或者通过下方链接联系我。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/873416
推荐阅读
相关标签
  

闽ICP备14008679号