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



授权登录获取头像及昵称 选择相册中的图片 点击动漫化按钮,调用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=thiswx.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界面。
效果如下:

2、avantar页面
<!--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>
其中 onload 函数接收 index 传递的 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(e) {let that = thisvar 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:function(e){var that = thisconsole.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)}})},

@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"] = 10resSets["resurl"] = "http://127.0.0.1:8090" +'/static/resImg/' + src_imgnamereturn json.dumps(resSets, ensure_ascii=False)
该代码主要接受前端传来的图片url,进行处理并且通过json传回去。
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 32sdef to_32s(x):return 256 if x < 256 else x - x%32img = cv2.resize(img, (to_32s(w), to_32s(h)))img = torch.from_numpy(img)img = img/127.5 - 1.0return imgdef 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.5out = np.clip(out, 0, 255).astype(np.uint8)cv2.imwrite(os.path.join(save_path, src_imgname), cv2.cvtColor(out, cv2.COLOR_BGR2RGB))
该代码主要是调用AnimeGanv2实现图像动漫化。? ?




分享

点收藏

点点赞

点在看
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号随时掌握互联网精彩
- 1 中央经济工作会议在北京举行 7904511
- 2 紧急提醒:请在日中国公民进行登记 7809102
- 3 电子体温计没水银体温计准?医生解答 7713147
- 4 “九天”无人机成功首飞 7616984
- 5 日本突发列车脱轨翻覆事故 7523921
- 6 断崖式降温!今冬最强寒潮来了 7424205
- 7 中央定调明年继续“国补” 7328576
- 8 北京延庆、房山等区已飘起雪花 7233767
- 9 女子买千元羽绒服穿1天变吸油服 7143008
- 10 寒潮来袭 “速冻”模式如何应对 7041848







AI100
