uni-app+flask 快速开发图像识别小程序

加上踩坑一共花了3个小时左右
代码已放置github https://github.com/dmhsq/image-recognition-flask-uniapp
效果如下
手机也跑通了 但是制作gif图麻烦 就电脑制作了
在这里插入图片描述

后端 (Python Flask)

在这里插入图片描述

获取百度ai开放平台应用密钥

打开这个地址https://console.bce.baidu.com/?fromai=1#/aip/overview
然后选择图像识别
在这里插入图片描述
如果没有应用 就创建
在这里插入图片描述有的话就点击应用列表
在这里插入图片描述
记住这里的
AppID

API Key

Secret Key

随机字符串产生器 (md5random.python文件)

保证每一个文件名都不一样

import random
import hashlib
def sjs():
    a = random.randint(0, 100)
    a = "a" + str(a);
    b = random.randint(100, 10000);
    b = "b" + str(b);
    c = hashlib.md5(a.encode(encoding='UTF-8')).hexdigest() + hashlib.md5(b.encode(encoding='UTF-8')).hexdigest();
    c = "c" + str(c);
    d = random.randint(10, 100);
    d = "d" + str(d);
    e = hashlib.md5(c.encode(encoding='UTF-8')).hexdigest() + hashlib.md5(d.encode(encoding='UTF-8')).hexdigest();
    e = hashlib.md5(e.encode(encoding='UTF-8')).hexdigest()
    return e;

封装api (AipImageClassify.py文件)

需要安装百度api

pip install baidu-aip

如果失效 手动安装
在这里插入图片描述

APP_ID
API_KEY
SECRET_KEY
这三个我们在第一步获取了

这里我们只调用了几个 想要调用更多 请参考官方文档
图像识别官方文档

from aip import AipImageClassify

""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'

client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)

def get_imgGeneral(type,image):
    if(type==0):
        return __animal(image)
    elif(type==1):
        return __dish(image)
    elif(type==2):
        return __car(image)
    elif(type==3):
        return __plant(image)
    elif(type==4):
        return __ingred(image)
    else:
        return "类型或图片格式错误"

""" 调用动物识别 """
def __animal(image):
    return client.animalDetect(image);

""" 调用菜品识别 """
def __dish(image):
    return client.dishDetect(image);

""" 调用车辆识别 """
def __car(image):
    return client.carDetect(image);

""" 调用植物识别 """
def __plant(image):
    return client.plantDetect(image);

""" 调用食材识别 """
def __ingred(image):
    return client.ingredient(image);

编写接口文件

from flask import Flask,request
import json,os
from AipImageClassify import get_imgGeneral
from md5random import sjs;
app = Flask(__name__)

@app.route("/file",methods=['POST'])
def upfile():
    '''获取文件'''
    params_file = request.files['file'];
    '''拼接得到文件应当在的路径'''
    dst = os.path.join(os.path.dirname(__file__),sjs()+params_file.name);
    '''存入本地'''
    params_file.save(dst)
    cont = "";
    with open(dst, 'rb') as file:
        '''获取文件二进制'''
        cont = file.read()
        '''打印方便观察 也知道程序进度'''
        print(cont)
    '''删除文件'''    
    os.remove(dst);
    '''获取表单数据type'''
    type=int(request.form['type'])
    '''打印方便观察 也知道程序进度'''
    print(cont)
    '''调用百度api并将结果转为json字符串并返回'''
    return json.dumps(get_imgGeneral(type,cont));
if __name__=='__main__':
        app.run(host='0.0.0.0',port=8086)

前端 (uni-app)

一共三个页面
首页(index),历史(mine),识别页(apiuse)
在这里插入图片描述

开发工具安装以及搭建项目

写过类似文章 请移步
开发工具安装
页面以及导航

首页

尽量节省代码量 所以新建项目后
就加了个 uni-list
根据文档说法 uni=list不需要再注册组件

<template>
	<view>
		<view class="content">
			<image class="logo" src="/static/main.jpg"></image>
			<view class="text-area">
				<text class="title">{
   
   {title}}</text>
			</view>
		</view>
		<uni-list>
			 <uni-list-item title="动物识别"  showArrow thumb="/static/img/animal.png" thumb-size="base" clickable @click="goSb(0)" />
			 <uni-list-item title="植物识别"  showArrow thumb="/static/img/botany.png" thumb-size="base" clickable @click="goSb(3)" />
			 <uni-list-item title="车辆识别"  showArrow thumb="/static/img/car.png" thumb-size="base" clickable @click="goSb(2)" />
			 <uni-list-item title="菜品识别"  showArrow thumb="/static/img/foods.png" thumb-size="base" clickable @click="goSb(1)" />
			 <uni-list-item title="果蔬识别"  showArrow thumb="/static/img/food.png" thumb-size="base" clickable @click="goSb(4)" />
			 <uni-list-item title="清除历史"  showArrow thumb="/static/img/laji.png" thumb-size="base" clickable @click="qclocal()" />
		</uni-list>
	</view>
</template>

历史

用到了tTable组件
需要到插件市场下载
插件市场地址 https://ext.dcloud.net.cn/plugin?id=413

注意

本地存储只能存储字符串
所以需要转换成json字符串 JSON.stringify(object)
使用时再转成json对象 JSON.parse(str)

<template>
	<view>
		<view class="content" v-if="tableList.length==0">
			<text class="title">您还没有识别哦~~~</text>
		</view>
		<view class="box" v-if="tableList.length>0">
		    <t-table @change="change">
		        <t-tr>
		            <t-th>时间</t-th>
		            <t-th>类型</t-th>
		            <t-th>最大可能</t-th>
		        </t-tr>
		        <t-tr v-for="item in tableList" :key="item.date">
		            <t-td>{
   
   { item.date }}</t-td>
		            <t-td>{
   
   { item.type }}</t-td>
		            <t-td>{
   
   { item.onebe}}</t-td>
		        </t-tr>
		    </t-table>        
		</view>
	</view>
</template>
<script>
	import tTable from '@/components/t-table/t-table.vue';
	import tTh from '@/components/t-table/t-th.vue';
	import tTr from '@/components/t-table/t-tr.vue';
	import tTd from '@/components/t-table/t-td.vue';   
	export default {
     
     
		components: {
     
     
		   tTable,
		   tTh,
		   tTr,
		   tTd        
		 }, 
		data() {
     
     
			return {
     
     
				tableList:[]
			}
		},
		onPullDownRefresh() {
     
     
			this.getData();
		},
		onLoad() {
     
     
			this.getData();
		},
		onShow() {
     
     
			this.getData();
		},
		methods: {
     
     
			getData(){
     
     
				uni.showLoading({
     
     
				    title: '加载中'
				});
				let vm = this;
				uni.getStorage({
     
     
					key:'historys',
					success: res=>{
     
     
						let datas = JSON.parse(res.data);
						uni.hideLoading();
						uni.stopPullDownRefresh();
						vm.tableList = datas;
					},
					fail:function(){
     
     
						vm.tableList = [];
						uni.hideLoading();	
						uni.stopPullDownRefresh();
					}
				})
			}
		}
	}
</script>

识别页

用到了tTable组件
需要到插件市场下载
插件市场地址 https://ext.dcloud.net.cn/plugin?id=413

<template>
	<view>
		<view class="content" :class="{bgs:(imgSrc!=''),ybgs:(imgSrc=='')}">
			<image class="logo" :src="imgSrc"></image>
		</view>
		<button @click="upfile()">上传图片</button>
		<view class="box" v-if="isHas">
		    <t-table @change="change">
		        <t-tr>
		            <t-th>序号</t-th>
		            <t-th>类型</t-th>
		            <t-th>可能性</t-th>
		        </t-tr>
		        <t-tr v-for="(item,index) in tableList" :key="item.name">
		            <t-td>{
   
   { index + 1 }}</t-td>
		            <t-td>{
   
   { item.name }}</t-td>
		            <t-td>{
   
   { item.score | dealVal}}</t-td>
		        </t-tr>
		    </t-table>        
		</view>
	</view>
</template>

上次图片功能

uni.chooseImage({
    
    
count: 1,
success: function (res) {
    
    
	console.log(res)
	vm.imgSrc = res.tempFilePaths[0];
	console.log(JSON.stringify(res.tempFilePaths));
	uni.uploadFile({
    
    
	//上次测试http://192.168.0.103:8086
	//云端忽略
	//手机调试需要修改ip地址
	url:'http://localhost:8086/file',
	filePath:res.tempFilePaths[0],
	name:'file',
	formData: {
    
    
		'type': 0             
	},
	success: (request) => {
    
    
		uni.showLoading({
    
    
			title: '加载中'
		});
		console.log(request.data)
		let str =  unescape(request.data.replace(/\\u/g, "%u"));
		let s = JSON.parse(str)
		uni.hideLoading();
		vm.tableList = s.result;
		vm.isHas = true;
			}
		})
	}
});							    	    
			

完整代码

这里不再放置 有需要去giyhub下载即可
https://github.com/dmhsq/image-recognition-flask-uniapp







  大家好,我是代码哈士奇,是一名软件学院网络工程的学生,因为我是“狗”,狗走千里吃肉。想把大学期间学的东西和大家分享,和大家一起进步。但由于水平有限,博客中难免会有一些错误出现,有纰漏之处恳请各位大佬不吝赐教!暂时只在csdn这一个平台进行更新,博客主页:https://blog.csdn.net/qq_42027681

未经本人允许,禁止转载

在这里插入图片描述


后续会推出

前端:vue入门 vue开发小程序 等
后端: java入门 springboot入门等
服务器:mysql入门 服务器简单指令 云服务器运行项目
python:推荐不温卜火 一定要看哦
一些插件的使用等

大学之道亦在自身,努力学习,热血青春
如果对编程感兴趣可以加入我们的qq群一起交流:974178910
在这里插入图片描述

有问题可以下方留言,看到了会回复哦

猜你喜欢

转载自blog.csdn.net/qq_42027681/article/details/112916576
今日推荐