caffe做的分类识别
2017年春节入坑DP,学着caffe做了一个杂草小苗的APP,模型和功能均在云端。pypic.py#!/usr/bin/env python#-*-coding:utf-8-*-import numpy as npimport sys,osimport re# 设置当前的工作环境在caffe下caffe_root = 'd:/caffe/caffe-master/'# 我们也把caffe/pyt
2017年春节入坑DP,学着caffe做了一个杂草小苗的APP,模型和功能均在云端。
pypic.py
#!/usr/bin/env python
#-*-coding:utf-8-*-
import numpy as np
import sys,os
import re
# 设置当前的工作环境在caffe下
caffe_root = 'caffe/caffe-master/'
# 我们也把caffe/python也添加到当前环境
sys.path.insert(0, caffe_root + 'python')
sys.path.insert(0, caffe_root + 'python/caffe')
# os.environ['GLOG_minloglevel'] = '2'
import caffe
os.chdir(caffe_root)#更换工作目录
#GPU模式
#caffe.set_device(0) # 如果你有多个GPU,那么选择第一个
caffe.set_mode_cpu()
# 设置网络结构
net_file=caffe_root + 'examples/flower/deploy.prototxt' #现成的
# 添加训练之后的参数
caffe_model=caffe_root + 'examples/flower/snapshot_iter_40000.caffemodel'
# 均值文件
mean_file=caffe_root + 'examples/flower/ilsvrc_2012_mean.npy'
# 这里对任何一个程序都是通用的,就是处理图片
# 把上面添加的两个变量都作为参数构造一个Net
net = caffe.Net(net_file,caffe_model,caffe.TEST)
# 得到data的形状,这里的图片是默认matplotlib底层加载的
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
# matplotlib加载的image是像素[0-1],图片的数据格式[weight,high,channels],RGB
# caffe加载的图片需要的是[0-255]像素,数据格式[channels,weight,high],BGR,那么就需要转换
# channel 放到前面
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))
# 图片像素放大到[0-255]
transformer.set_raw_scale('data', 255)
# RGB-->BGR 转换
transformer.set_channel_swap('data', (2,1,0))
# print "input image" + sys.argv[1]
# 这里才是加载图片
#im=caffe.io.load_image(caffe_root+'examples/flower/jpg/zshuhe055.jpg')
im=caffe.io.load_image(sys.argv[1])
# 用上面的transformer.preprocess来处理刚刚加载图片
net.blobs['data'].data[...] = transformer.preprocess('data',im)
#注意,网络开始向前传播啦
output = net.forward()
# 最终的结果: 当前这个图片的属于哪个物体的概率(列表表示)
output_prob = output['prob'][0]
# 找出最大的那个概率
# print 'predicted class is:', output_prob.argmax()
# 也可以找出前五名的概率
top_inds = output_prob.argsort()[::-1][:5]
# 最后加载数据集进行验证
imagenet_labels_filename = caffe_root + 'examples/flower/synset_words.txt'
labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t')
# print 'probabilities and labels:'
# zip(output_prob[top_inds], labels[top_inds])
top_k = net.blobs['prob'].data[0].flatten().argsort()[-1:-6:-1]
#for i in np.arange(top_k.size):
# print labels[top_k[i]]
with open("pestTemp.txt", "w") as f:
# f.write(''.join(labels[top_k[0]])+';'.join(labels[top_k[1]])+';'.join(labels[top_k[2]])+';'.join(labels[top_k[3]])+';'.join(labels[top_k[4]]))
f.write(labels[top_k[0]]+';'+labels[top_k[1]]+';'+labels[top_k[2]]+';'+labels[top_k[3]]+';'+labels[top_k[4]])
upImgAi.php
date_default_timezone_set('Asia/Shanghai');
require_once('../include/DbMysqli.php');//BbsDbclass
require_once("PYClass.php");
//post 传值
$tblId = $_POST['tblId'];
$act = $_POST['act'];
$imgtxt = $_POST['imgtxt'];
$UpPest = $_POST['UpPest'];
$recId = $_POST['recId'];
$UpLoc = $_POST['UpLoc'];
$UpImgName = $_FILES["image"]["name"];
$UpAiDir = 'caffe/caffe-master/examples/flower/AiImg/';
if(!file_exists($UpAiDir)) {
mkdir($UpAiDir); //新建文件夹
}
UpImgFile($UpImgName,$UpAiDir);//上传图片到指定目录
$pestImg = $UpAiDir.$UpImgName;
system("python pypic.py ".$pestImg, $ret);
$pyDlFile = "caffe/caffe-master/pestTemp.txt"; //结果
if(file_exists($pyDlFile)){ //文件内容读入到字符串
$dlStr = file_get_contents($pyDlFile);
$dlStr = preg_replace('|[0-9]+|','',$dlStr);
$dlPestArr = explode(";",$dlStr); //诊断结果数组
AiJson($dlPestArr);
}
function UpImgFile($TempName,$UpAiDir){//上传图片移到指定目录
if(move_uploaded_file($_FILES['image']['tmp_name'], $UpAiDir.$TempName)){
//echo "The file ".basename($TempName)." has been uploaded successful.";
}else{
echo "Sorry, there was a problem uploading your file.failed";
}
}
function AiJson($dlPestArr){
$response = array();//zsh;yc;znB;zyy;ehm
$pestArrEn = array('jc','zyy','dzZ','znA','zsh','dzB','pop','yc','znB','fl','ehm','zjym','mg','dzC','cec','dm','fs','dqb','ze','zheqi','znC','znZ','dzA','bph','sbph');
$pestArr = array('荠菜','猪殃殃','0级稻桩','1级子囊','早熟禾','2级稻桩','婆婆纳','硬草','2级子囊','繁缕','二化螟','纵卷叶螟','毛茛','3级稻桩','刺儿菜','大螟','褐稻虱','稻曲病','卷耳','泽漆','3级子囊','0级子囊','1级稻桩','褐飞虱','灰飞虱');
for($i=0;$i<count($dlPestArr);$i++){
$RecArr["Id"] = "1";//表ID序号
$RecArr["demoImg"] = "http://localhost/jsipm/admin/".$dlPestArr[$i].".jpg"; //图标
if(in_array($dlPestArr[$i],$pestArrEn)){
$pId = array_search($dlPestArr[$i],$pestArrEn);
$RecArr["ShowTbl"] = $pestArr[$pId]; //诊断结果
}else{
$RecArr["ShowTbl"] = "未知"; //诊断结果
}
$RecArr["RealTbl"] = "http://localhost/jsipm/pestimg/csvpro.mp4"; //表格名
array_push($response, $RecArr);
}
$JsonStr = json_encode($response);
echo $JsonStr;
}
致敬贾神!
更多推荐
所有评论(0)