微信小程序调用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 SQLAlchemy基本操作和常用技巧(包含大量实例,非常好)
May 06 Python
极简的Python入门指引
Apr 01 Python
python实现读取命令行参数的方法
May 22 Python
举例讲解Python设计模式编程中的访问者与观察者模式
Jan 26 Python
python实现识别相似图片小结
Feb 22 Python
python字符串,数值计算
Oct 05 Python
Python实现返回数组中第i小元素的方法示例
Dec 04 Python
解决pycharm启动后总是不停的updating indices...indexing的问题
Nov 27 Python
如何基于python对接钉钉并获取access_token
Apr 21 Python
Python做图像处理及视频音频文件分离和合成功能
Nov 24 Python
解析目标检测之IoU
Jun 26 Python
Django框架中模型的用法
Jun 10 Python
使用python绘制分组对比柱状图
使用python将HTML转换为PDF pdfkit包(wkhtmltopdf) 的使用方法
Apr 21 #Python
Python尝试实现蒙特卡罗模拟期权定价
Python matplotlib绘制条形统计图 处理多个实验多组观测值
python绘制简单直方图(质量分布图)的方法
Python绘制散乱的点构成的图的方法
Python可视化动图组件ipyvizzu绘制惊艳的可视化动图
You might like
php ftp文件上传函数(基础版)
2010/06/03 PHP
PHP中单引号与双引号的区别分析
2014/08/19 PHP
Yii使用find findAll查找出指定字段的实现方法
2014/09/05 PHP
php学习笔记之基础知识
2014/11/08 PHP
PHP的Laravel框架中使用消息队列queue及异步队列的方法
2016/03/21 PHP
php usort 使用用户自定义的比较函数对二维数组中的值进行排序
2017/05/02 PHP
PHP数组式访问接口ArrayAccess用法分析
2017/12/28 PHP
一个高效的JavaScript压缩工具下载集合
2007/03/06 Javascript
加载jQuery后$冲突的解决办法
2010/07/09 Javascript
浅谈JavaScript Date日期和时间对象
2014/12/29 Javascript
基于jQuery实现左右图片轮播(原理通用)
2015/12/24 Javascript
js 性能优化之算法和流程控制
2017/02/15 Javascript
vue中$set的使用(结合在实际应用中遇到的坑)
2018/07/10 Javascript
基于vue cli 通过命令行传参实现多环境配置
2018/07/12 Javascript
对angularJs中$sce服务安全显示html文本的实例
2018/09/30 Javascript
vue2.0项目集成Cesium的实现方法
2019/07/30 Javascript
javascript设计模式 ? 建造者模式原理与应用实例分析
2020/04/10 Javascript
[01:38]女王驾到——至宝魔廷新尊技能&特效展示
2020/06/16 DOTA
浅谈django2.0 ForeignKey参数的变化
2019/08/06 Python
解决python中import文件夹下面py文件报错问题
2020/06/01 Python
Tensorflow--取tensorf指定列的操作方式
2020/06/30 Python
SpringBoot首页设置解析(推荐)
2021/02/11 Python
Flask中jinja2的继承实现方法及实例
2021/03/03 Python
Casetify官网:自制专属手机壳、iPad护壳和Apple Watch手表带
2018/05/09 全球购物
哈曼俄罗斯官方网上商店:Harman.club
2020/07/24 全球购物
专升本个人自我评价
2013/12/22 职场文书
《三个小伙伴》教学反思
2014/04/11 职场文书
小学绿色学校申报材料
2014/08/23 职场文书
教师四风问题对照检查材料
2014/09/26 职场文书
论群众路线学习心得体会
2014/10/31 职场文书
大学生十八大感想
2015/08/11 职场文书
小学生必读成语故事大全:送给暑假的你们
2019/07/09 职场文书
导游词之寿县报恩寺
2020/01/19 职场文书
mysql批量新增和存储的方法实例
2021/04/07 MySQL
Linux7.6二进制安装Mysql8.0.27详细操作步骤
2021/11/27 MySQL
默认网关不可用修复后过一会又不好使了解决方法
2022/04/08 数码科技