微信小程序调用python模型


Posted in Python onApril 21, 2022

需求:

小程序端拍照调用python训练好的图片分类模型。实现图片分类识别的功能。

微信小程序端:

重点在chooseImage函数中,根据图片路径获取到图片传递给flask的url;

Page({
    data: {
        SHOW_TOP: true,
        canRecordStart: false,
    },
    data: {
        tempFilePaths:'',
        sourceType: ['camera', 'album']
      },
    isSpeaking: false,
    accessToken: "",
    onLoad: function (options) {
        
        console.log("onLoad!");
        this.setHeader();
        var that=this
        wx.showShareMenu({
            withShareTicket: true //要求小程序返回分享目标信息
        });
        var isShowed = wx.getStorageSync("tip");
        if (isShowed != 1) {
            setTimeout(() => {
                this.setData({
                    SHOW_TOP: false
                })
                wx.setStorageSync("tip", 1)
            }, 3 * 1000)
        } else {
            this.setData({
                SHOW_TOP: false
            })
        };
    },
    },
    
 //头像点击处理事件,使用wx.showActionSheet()调用菜单栏
 buttonclick: function () {
    const that = this
    wx.showActionSheet({
      itemList: ['拍照', '相册'],
      itemColor: '',
      //成功时回调
      success: function (res) {
        if (!res.cancel) {
          /*
           res.tapIndex返回用户点击的按钮序号,从上到下的顺序,从0开始
           比如用户点击本例中的拍照就返回0,相册就返回1
           我们res.tapIndex的值传给chooseImage()
          */
          that.chooseImage(res.tapIndex)
        }
      },
      
setHeader(){
    const tempFilePaths = wx.getStorageSync('tempFilePaths');
    if (tempFilePaths) {
      this.setData({
        tempFilePaths: tempFilePaths
      })
    } else {
      this.setData({
        tempFilePaths: '/images/camera.png'
      })
    }
  },

  chooseImage(tapIndex) {
    const checkeddata = true
    const that = this
    wx.chooseImage({
    //count表示一次可以选择多少照片
      count: 1,
      //sizeType所选的图片的尺寸,original原图,compressed压缩图
      sizeType: ['original', 'compressed'],
      //如果sourceType为camera则调用摄像头,为album时调用相册
      sourceType: [that.data.sourceType[tapIndex]],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        console.log(res);
        const tempFilePaths = res.tempFilePaths
        //将选择到的图片缓存到本地storage中
        wx.setStorageSync('tempFilePaths', tempFilePaths)
        /*
		由于在我们选择图片后图片只是保存到storage中,所以我们需要调用一次   	        setHeader()方法来使页面上的头像更新
		*/
        that.setHeader();
        // wx.showToast({
        //   title: '设置成功',
        //   icon: 'none',
        // //   duration: 2000
        // })
        wx.showLoading({
            title: '识别中...',
        })
        
        var team_image = wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], "base64")
        wx.request({
          url: 'http://127.0.0.1:5000/upload', //API地址,upload是我给路由起的名字,参照下面的python代码
                     method: "POST",
          header: {
                     'content-type': "application/x-www-form-urlencoded",
                    },
          data: {image: team_image},//将数据传给后端
     
        success: function (res) {
            console.log(res.data);  //控制台输出返回数据  
            wx.hideLoading()
            wx.showModal({

                title: '识别结果', 
                confirmText: "识别正确",
                cancelText:"识别错误",
                content: res.data, 
                success: function(res) { 
                if (res.confirm) {
                console.log('识别正确')
                } else if (res.cancel) {
                console.log('重新识别')
                }
                }
                })     
          }
        })
      }
    })
  },
});

flask端:

将图片裁剪,填充,调用自己训练保存最优的模型,用softmax处理结果矩阵,最后得到预测种类

# coding=utf-8
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
from datetime import timedelta
from flask import Flask, render_template, request
import torchvision.transforms as transforms
from PIL import Image
from torchvision import models
import os
import torch
import json
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
import base64

app = Flask(__name__)

def softmax(x):
    exp_x = np.exp(x)
    softmax_x = exp_x / np.sum(exp_x, 0)
    return softmax_x

with open('dir_label.txt', 'r', encoding='utf-8') as f:
    labels = f.readlines()
    print("oldlabels:",labels)
    labels = list(map(lambda x: x.strip().split('\t'), labels))
    print("newlabels:",labels)

def padding_black(img):
    w, h = img.size

    scale = 224. / max(w, h)
    img_fg = img.resize([int(x) for x in [w * scale, h * scale]])

    size_fg = img_fg.size
    size_bg = 224

    img_bg = Image.new("RGB", (size_bg, size_bg))

    img_bg.paste(img_fg, ((size_bg - size_fg[0]) // 2,
                              (size_bg - size_fg[1]) // 2))

    img = img_bg
    return img
# 输出
@app.route('/')
def hello_world():
    return 'Hello World!'

# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)

# 添加路由
@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        # 通过file标签获取文件
        team_image = base64.b64decode(request.form.get("image"))  # 队base64进行解码还原。
        with open("static/111111.jpg", "wb") as f:
            f.write(team_image)
        image = Image.open("static/111111.jpg")
        # image = Image.open('laji.jpg')
        image = image.convert('RGB')
        image = padding_black(image)
        transform1 = transforms.Compose([
            transforms.Resize(224),
            transforms.ToTensor(),
        ])
        image = transform1(image)
        image = image.unsqueeze(0)
        # image = torch.unsqueeze(image, dim=0).float()
        print(image.shape)
        model = models.resnet50(pretrained=False)
        fc_inputs = model.fc.in_features
        model.fc = nn.Linear(fc_inputs, 214)
        # model = model.cuda()
        # 加载训练好的模型
        checkpoint = torch.load('model_best_checkpoint_resnet50.pth.tar')
        model.load_state_dict(checkpoint['state_dict'])
        model.eval()

        src = image.numpy()
        src = src.reshape(3, 224, 224)
        src = np.transpose(src, (1, 2, 0))
        # image = image.cuda()
        # label = label.cuda()
        pred = model(image)
        pred = pred.data.cpu().numpy()[0]

        score = softmax(pred)
        pred_id = np.argmax(score)

        plt.imshow(src)
        print('预测结果:', labels[pred_id][0])
        # return labels[pred_id][0];
        return json.dumps(labels[pred_id][0], ensure_ascii=False)//将预测结果传回给前端
        # plt.show()
    #     return render_template('upload_ok.html')
    #     重新返回上传界面
    # return render_template('upload.html')

if __name__ == '__main__':
    app.run(debug=False)

大致的效果:

微信小程序调用python模型

微信小程序调用python模型

但是在手机上测试的话,wx.request{}里的url的域名不规范,不能出现这种端口号,目前还在想解决办法,有知道的大佬还望告知。

总结

到此这篇关于微信小程序前端如何调用python后端模型的文章就介绍到这了!


Tags in this post...

Python 相关文章推荐
python pdb调试方法分享
Jan 21 Python
python使用心得之获得github代码库列表
Jun 25 Python
Python set集合类型操作总结
Nov 07 Python
部署Python的框架下的web app的详细教程
Apr 30 Python
Python的组合模式与责任链模式编程示例
Feb 02 Python
详解Python各大聊天系统的屏蔽脏话功能原理
Dec 01 Python
Python实现爬虫从网络上下载文档的实例代码
Jun 13 Python
pandas分区间,算频率的实例
Jul 04 Python
Python入门Anaconda和Pycharm的安装和配置详解
Jul 16 Python
python使用pip安装SciPy、SymPy、matplotlib教程
Nov 20 Python
pytorch 求网络模型参数实例
Dec 30 Python
python PyAUtoGUI库实现自动化控制鼠标键盘
Sep 09 Python
使用python绘制分组对比柱状图
使用python将HTML转换为PDF pdfkit包(wkhtmltopdf) 的使用方法
Apr 21 #Python
Python尝试实现蒙特卡罗模拟期权定价
Python matplotlib绘制条形统计图 处理多个实验多组观测值
python绘制简单直方图(质量分布图)的方法
Python绘制散乱的点构成的图的方法
Python可视化动图组件ipyvizzu绘制惊艳的可视化动图
You might like
实现dedecms全站URL静态化改造的代码
2007/03/29 PHP
利用PHP fsockopen 模拟POST/GET传送数据的方法
2015/09/22 PHP
$.get获取一个文件的内容示例代码
2013/09/11 Javascript
利用jquery.qrcode在页面上生成二维码且支持中文
2014/02/12 Javascript
js监听鼠标事件控制textarea输入字符串的个数
2014/09/29 Javascript
Windows系统中安装nodejs图文教程
2015/02/28 NodeJs
jQuery聚合函数实例
2015/05/21 Javascript
浅谈angularJS 作用域
2015/07/05 Javascript
H5移动端图片压缩上传开发流程
2016/11/09 Javascript
js中的eval()函数把含有转义字符的字符串转换成Object对象的方法
2016/12/02 Javascript
鼠标拖动改变DIV等网页元素的大小的实现方法
2017/07/06 Javascript
JS实现的简单下拉框联动功能示例
2018/05/11 Javascript
javascript刷新父页面方法汇总详解
2019/10/10 Javascript
vue 翻页组件vue-flip-page效果
2020/02/05 Javascript
Vue过渡效果之CSS过渡详解(结合transition,animation,animate.css)
2020/02/05 Javascript
vue打开子组件弹窗都刷新功能的实现
2020/09/21 Javascript
[07:03]显微镜下的DOTA2第九期——430圣堂刺客杀戮秀
2014/06/20 DOTA
python 从远程服务器下载日志文件的程序
2013/02/10 Python
使用Python写个小监控
2016/01/27 Python
详解Python读取配置文件模块ConfigParser
2017/05/11 Python
Python动态生成多维数组的方法示例
2018/08/09 Python
python3爬虫获取html内容及各属性值的方法
2018/12/17 Python
关于Python核心框架tornado的异步协程的2种方法详解
2019/08/28 Python
使用 PyTorch 实现 MLP 并在 MNIST 数据集上验证方式
2020/01/08 Python
VS2019+python3.7+opencv4.1+tensorflow1.13配置详解
2020/04/16 Python
Python使用Paramiko控制liunx第三方库
2020/05/20 Python
Ref与out有什么不同
2012/11/24 面试题
厨房领班竞聘演讲稿
2014/04/23 职场文书
关于责任的演讲稿
2014/05/20 职场文书
办公楼租房协议书范本
2014/11/25 职场文书
民主生活会汇报材料
2014/12/15 职场文书
医者仁心观后感
2015/06/17 职场文书
工作简报格式范文
2015/07/21 职场文书
《穷人》教学反思
2016/02/19 职场文书
Python代码,能玩30多款童年游戏!这些有几个是你玩过的
2021/04/27 Python
Win11软件图标固定到任务栏
2022/04/19 数码科技