找回密码
 立即注册

万粉博主推荐,微信小程序 +Flask 后端调用 AnimeGanV2

匿名  发表于 2022-1-14 21:20:12 阅读模式 打印 上一主题 下一主题
CSDN博客 |云领主

做一个小法式,间接在手机端就能一键天生专属于自己的动漫头像,下面是展现结果!!!

万粉博主保举,微信小法式 +Flask 后端挪用 AnimeGanV2-1.jpg



焦点功用设想

该小法式想要实现的是将微信头像大概挑选相册中的照片动漫化,所以拆解需求后,整理的焦点功用以下:

  • 授权登录获得头像及昵称
  • 挑选相册中的图片
  • 点击动漫化按钮,挪用Flask后端天生图像
  • 保存图像


微信小法式前端实现步调

首先新建一个空缺的微信小法式项目
1、登录界面
在 pages/index/index.wxml 设想页面:
<view wx:if="{{canIUse}}">    <view class='header'>        <view class="userinfo-avatar">            <open-data type="userAvatarUrl"></open-data>        </view>    </view>    <view class="content">        <view>申请获得以下权限</view>        <text>获得您的公然信息(昵称,头像等)</text>    </view>    <button wx:if="{{canIUse}}" class="loginBtn" type="primary"  lang="zh_CN" bindtap="bindGetUserProfile" >        授权登录    </button>在 pages/index/index.js 增加用户信息考证:
    bindGetUserProfile(e)     //当用户点击授权登录按钮触发 bindGetUserInfo函数    {      var that=this      wx.getUserProfile({          desc: '用于完善会员材料', // 声明获得用户小我信息后的用处,后续会展现在弹窗中,请谨慎填写          success: (res) => {          // console.log(res.userInfo)          var avantarurl=res.userInfo.avatarUrl;           wx.navigateTo({            url: '../../pages/change/change?url='+ avantarurl ,          })          },          fail:(res)=>{            console.log(1)          }        })    },其中将头像的url传递给avanta界面。
结果以下:

万粉博主保举,微信小法式 +Flask 后端挪用 AnimeGanV2-2.jpg

2、前置页面
在该页面停止拔取照片以及头像动漫化。
在 pages/avantar/avantar.wxml 设想页面:
<!--pages/avantar/avantar.wxml--><view class='preview'>    <view class="Imgtag">        <image class="tag" src='{{prurl}}' mode='aspectFit'></image>    </view>    <view class="bottomAll">        <button bindtap='selectImg' class="saveBtn">挑选图片</button>        <button bindtap='generateAvantar' class="saveBtn">动漫化</button>        <button bindtap='save' class="saveBtn">保存头像</button>    </view></view>在 pages/avantar/avantar.js 界说函数:
其中 onload 函数接收索引 传递的 url。
  onLoad: function (options) {    if(options.url){        // console.log(options.url)        var path = this.headimgHD(options.url)        console.log(path)        this.setData({            image:path,            // image1:path,            // baseURL:path        })    }其中 chooseImage函数实现挑选图片。
  chooseImage() {    var that = this;    wx.showActionSheet({      itemList: ['从相册当挑选', '摄影'],      itemColor: "#FAD143",      success: function (res) {        if (!res.cancel) {          wx.showLoading({            title: '正在读取...',          })          if (res.tapIndex == 0) {            that.chooseWxImage1('album', 1)          } else if (res.tapIndex == 1) {            that.chooseWxImage1('camera', 1)          }        }      }    })  },savePic函数保存照片。
  savePic(e) {    let that = this    var baseImg = that.data.baseImg    //保存图片    var save = wx.getFileSystemManager();    var number = Math.random();    save.writeFile({      filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',      data: baseImg,      encoding: 'base64',      success: res => {        wx.saveImageToPhotosAlbum({          filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',          success: function (res) {            wx.showToast({              title: '保存成功',            })          },          fail: function (err) {            console.log(err)          }        })        console.log(res)      },      fail: err => {        console.log(err)      }    })  },generateAvantar函数挪用postdata函数实现头像动漫化。
    generateAvantar:function(e){      var that = this      console.log(that.data.prurl)      wx.uploadFile({        url: 'http://127.0.0.1:8090/postdata',        filePath: that.data.prurl,        name: 'content',        success: function (res) {          console.log(res.data);          var resurl=JSON.parse(res.data)['resurl']           that.setData({            prurl: resurl          })          if (res) {             wx.showToast({              title: '转换完成',              duration: 3000            });          }        },        fail: (res) =>{          console.log('fail===',res)        }      })    },


Flask后端实现步调



1、设置RESTful路由方式
@app.route('/postdata', methods=['POST'])def postdata():    f = request.files['content']    print(f)    user_input = request.form.get("name")    basepath = os.path.dirname(__file__)  # 当前文件地点途径    src_imgname = str(uuid.uuid1()) + ".jpg"    upload_path = os.path.join(basepath, 'static/srcImg/')        if os.path.exists(upload_path)==False:        os.makedirs(upload_path)    f.save(upload_path + src_imgname)    # img = cv2.imread(upload_path + src_imgname, 1)     save_path = os.path.join(basepath, 'static/resImg/')    if os.path.exists(save_path) == False:        os.makedirs(save_path)    generateAvantar(src_imgname,upload_path,save_path)    resSets["value"] = 10    resSets["resurl"] = "http://127.0.0.1:8090" +'/static/resImg/' + src_imgname    return json.dumps(resSets, ensure_ascii=False)该代码首要接管前端传来的图片url,停止处置而且经过json传回去。
2、挪用AnimeGanv2实现动漫化
net = Generator()net.load_state_dict(torch.load(args.checkpoint, map_location="cpu"))net.to(args.device).eval()# print(f"model loaded: {args.checkpoint}") # os.makedirs(args.output_dir, exist_ok=True)    def load_image(image_path, x32=False):    img = cv2.imread(image_path).astype(np.float32)    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)    h, w = img.shape[:2]     if x32: # resize image to multiple of 32s        def to_32s(x):            return 256 if x < 256 else x - x%32        img = cv2.resize(img, (to_32s(w), to_32s(h)))     img = torch.from_numpy(img)    img = img/127.5 - 1.0    return img def generateAvantar(src_imgname,upload_path,save_path):        image = load_image((upload_path+src_imgname), args.x32)    with torch.no_grad():        input = image.permute(2, 0,                     1).unsqueeze(0).to(args.device)        out = net(input, args.upsample_align).squeeze(0).permute(1, 2, 0).cpu().numpy()        out = (out + 1)*127.5        out = np.clip(out, 0, 255).astype(np.uint8)    cv2.imwrite(os.path.join(save_path, src_imgname), cv2.cvtColor(out, cv2.COLOR_BGR2RGB))该代码主如果挪用AnimeGanv2实现图像动漫化。
最初实现结果:

万粉博主保举,微信小法式 +Flask 后端挪用 AnimeGanV2-3.jpg



总结

实在这个小法式实现起来并不是很难,只需要设置根本的深度进修情况和Flask编程就行了,再领会一些小法式根基的api,就可以开辟出来,大师偶然候的可以去试试,背景我已经搭好了,大师可以间接利用,可以看看结果。有什么题目可以在批评区留言~
回复

使用道具

说点什么

您需要登录后才可以回帖 登录 | 立即注册
HOT • 推荐

神回复

站长姓名:王殿武 杭州共生网络科技 创始人 云裂变新零售系统 创始人 飞商人脉对接平台 创始人 同城交友聚会平台 创始人 生活经验分享社区 创始人 合作微信:15924191378(注明来意)