tensorflow利用预训练模型进行目标检测(三):将检测结果存入mysql数据库
mysql版本:5.7 ; 数据库:rdshare;表captain_america3_sd用来记录某帧是否被检测。表captain_america3_d用来记录检测到的数据。
python模块,包部分内容参考http://www.runoob.com/python/python-modules.html https://www.cnblogs.com/ningskyer/articles/6025964.html
一、连接数据库
参考:
# 将视频插入数据库
def video_insert(filename,couse_id):
conn =MySQLdb.connect(user='root',passwd='****',host='sh-cdb-myegtz7i.sql.tencentcdb.com',port=63619,db='bitbear',charset='utf8')
cursor = conn.cursor() # 查找课程报告表中courseh_id等于解析得到的course_id的记录,得到courser_id
# courseh_id是课程记录表中的course_id;courser_id是课程报告表中的主键;course_id是本程序中
sql="SELECT courser_id FROM course_report WHERE courseh_id ='%s' "% (couse_id);
cursor.execute(sql)
results = cursor.fetchall()
if(results):
print(results)
courser_id=results[0][0]
print(results[0][0]) # 获取该文件的路径
#rarpath = os.getcwd();
rarpath =filename
print(rarpath) # 将记录插入
#try:
sql="UPDATE course_report SET json = '%s' WHERE courser_id = '%s' " % (rarpath,courser_id)
cursor.execute(sql)
cursor.rowcount
conn.commit()
cursor.close()
首先需要安装mysql驱动 sudo apt-get install python-mysqldb
# 将detection的结果存入mysql数据库
def detection_to_database(object_name):
conn =MySQLdb.connect(user='root',passwd='****',host='localhost',port=3306,db='rdshare',charset='utf8')
cursor = conn.cursor() #sql="SELECT person FROM captain_america3_d WHERE id =1 ";
#cursor.execute(sql)
#results = cursor.fetchall()
#if(results):
# print(results) sql="INSERT INTO captain_america3_sd (is_detected) VALUES (1)"
cursor.execute(sql)
cursor.rowcount
conn.commit()
cursor.close()
二、修改文件结构
在同一目录下新建detection_control.py文件,相当于main文件,控制detection的流程,读入参数
#!usr/bin/python
# -*- coding: utf-8 -*- import datetime
import os
import time
import argparse
import detection as mod_detection
import sys
reload(sys)
sys.setdefaultencoding('utf8') os.environ['TF_CPP_MIN_LOG_LEVEL']='' def parse_args():
'''parse args'''
parser = argparse.ArgumentParser()
parser.add_argument('--image_path', default='/home/yanjieliu/rdshare/dataset/ca36000_36100/')
parser.add_argument('--image_start_num', default='')
parser.add_argument('--image_end_num', default='')
parser.add_argument('--model_name',
default='ssd_inception_v2_coco_2018_01_28')
return parser.parse_args() if __name__ == '__main__':
# 运行
args=parse_args()
for frame_num in range(int(args.image_start_num),int(args.image_end_num)):
print(frame_num)
#调用detection.py文件中的Detection函数,并向其传递参数
mod_detection.Detection(args, frame_num)
调用detection.py中的Detection函数,进行识别
detection.py文件内容如下
#!usr/bin/python
# -*- coding: utf-8 -*- import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
from matplotlib import pyplot as plt
import os
import tensorflow as tf
from PIL import Image
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util import datetime
# 关闭tensorflow警告
import time
import MySQLdb
import argparse
import sys
reload(sys)
sys.setdefaultencoding('utf8') os.environ['TF_CPP_MIN_LOG_LEVEL']='' detection_graph = tf.Graph() # 将detection的结果存入mysql数据库
def detection_to_database(object_name, frame_num):
conn =MySQLdb.connect(user='root',passwd='****',host='localhost',port=3306,db='rdshare',charset='utf8')
cursor = conn.cursor() #查询目标检测状态表,查看frame_num是否已经被检测过,若是,则更新,若否,则插入
sql="SELECT is_detected FROM captain_america3_sd WHERE frame_num ='%s' "% (frame_num);
cursor.execute(sql)
results = cursor.fetchall()
if(results):
print(results)
sql="UPDATE captain_america3_sd SET is_detected=1";
else:
print('null')
sql="INSERT INTO captain_america3_sd (is_detected, frame_num) VALUES (1,'%s')"%(frame_num); cursor.execute(sql) cursor.rowcount
conn.commit()
cursor.close() # 加载模型数据-------------------------------------------------------------------------------------------------------
def loading(model_name): with detection_graph.as_default():
od_graph_def = tf.GraphDef()
PATH_TO_CKPT = '/home/yanjieliu/models/models/research/object_detection/pretrained_models/'+model_name + '/frozen_inference_graph.pb'
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return detection_graph # Detection检测-------------------------------------------------------------------------------------------------------
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('/home/yanjieliu/models/models/research/object_detection/data', 'mscoco_label_map.pbtxt')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=90, use_display_name=True)
category_index = label_map_util.create_category_index(categories) def Detection(args, frame_num):
image_path=args.image_path
loading(args.model_name)
#start = time.time()
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
# for image_path in TEST_IMAGE_PATHS:
image = Image.open('%simage-%s.jpeg'%(image_path, frame_num)) # the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image) # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular object was detected.
boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection.
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection.将识别结果标记在图片上
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8)
# output result输出
for i in range(3):
if classes[0][i] in category_index.keys():
class_name = category_index[classes[0][i]]['name']
detection_to_database(class_name, frame_num)
else:
class_name = 'N/A'
print("object:%s gailv:%s" % (class_name, scores[0][i])) # matplotlib输出图片
# Size, in inches, of the output images.
IMAGE_SIZE = (20, 12)
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np)
plt.show() def parse_args():
'''parse args'''
parser = argparse.ArgumentParser()
parser.add_argument('--image_path', default='/home/yanjieliu/rdshare/dataset/ca36000_36100/')
parser.add_argument('--image_start_num', default='')
parser.add_argument('--image_end_num', default='')
parser.add_argument('--model_name',
default='ssd_inception_v2_coco_2018_01_28')
return parser.parse_args() if __name__ == '__main__':
# 运行
args=parse_args()
start = time.time()
Detection(args, frame_num)
end = time.time()
print('time:\n')
print str(end-start) #将时间写入到文件,方便统计
# with open('./outputs/1to10test_outputs.txt', 'a') as f:
# f.write('\n')
# f.write(str(end-start))
tensorflow利用预训练模型进行目标检测(三):将检测结果存入mysql数据库的更多相关文章
- tensorflow利用预训练模型进行目标检测(一):安装tensorflow detection api
一.tensorflow安装 首先系统中已经安装了两个版本的tensorflow,一个是通过keras安装的, 一个是按照官网教程https://www.tensorflow.org/install/ ...
- tensorflow利用预训练模型进行目标检测(二):预训练模型的使用
一.运行样例 官网链接:https://github.com/tensorflow/models/blob/master/research/object_detection/object_detect ...
- tensorflow利用预训练模型进行目标检测(四):检测中的精度问题以及evaluation
一.tensorflow提供的evaluation Inference and evaluation on the Open Images dataset:https://github.com/ten ...
- 利用PHP实现登录与注册功能以及使用PHP读取mysql数据库——以表格形式显示数据
登录界面 <body><form action="login1.php" method="post"><div>用户名:&l ...
- C# | VS2019连接MySQL的三种方法以及使用MySQL数据库教程
本文将介绍3种添加MySQL引用的方法,以及连接MySQL和使用MySQL的教程 前篇:Visual Studio 2019连接MySQL数据库详细教程 \[QAQ \] 第一种方法 下载 Mysql ...
- caffe-ssd使用预训练模型做目标检测
首先参考https://www.jianshu.com/p/4eaedaeafcb4 这是一个傻瓜似的目标检测样例,目前还不清楚图片怎么转换,怎么验证,后续继续跟进 模型测试(1)图片数据集上测试 p ...
- redis(三)--用Redis作为Mysql数据库的缓存
把MySQL结果集缓存到Redis的字符串或哈希结构中以后,我们面临一个新的问题,即如何为这些字符串或哈希命名,也就是如何确定它们的键.因为这些数据结构所对应的行都属于某个结果集,假如可以找到一种唯一 ...
- solr学习篇(三) solr7.4 连接MySQL数据库
目录 导入相关jar包 配置连接信息 将数据库导入到solr中 验证是否成功 创建一个Core,创建Core的方法之前已经很详细的讲解过了,如果还是不清楚请参考 solr7.4 安装配置篇: 1.导入 ...
- 三、Navicat将远程MySql数据库数据导入本地
1.安装本地的MySql.记住用户名和密码,这里以root,root为例. 2.打开Navicat,新建连接(连接),输入连接名,用户名,密码.确定,连接测试.这里连接名为luzhanshi.这样本地 ...
随机推荐
- 动画和图形:OpenGL ES
在网络层,互联网提供所有应用程序都要使用的两种类型的服务,尽管目前理解这些服务的细节并不重要,但在所有TCP/IP概述中,都不能忽略他们: 无连接分组交付服务(Connectionless Packe ...
- Kettle bug收集
20160919(未确定): 加载表的使用"Use batch update for inserts"会引致奇怪的转换失败? 出错日志: - linenr 450000- line ...
- 用python(2.7)自定义实现SQL的集合操作
有的时候需要在不同的数据库实例之间做集合操作,这就无法直接使用SQL语句的join,left join了.相同类型的数据库之间虽然也有类似于DBLINK和FEDERATED之类的东西,但一来这些东西不 ...
- outlook 2010 搜索不到邮件
打开outlook 2010 文件, 选项, 加载项, 转到 windows search eamil indexer(打勾) 关闭outlook 控制面板, 索引选项, 高级, 重建索引
- 重载(overload)和重写(override)的对比(笔试经常出)
Day04_SHJavaTraing_4-6-2017 1.重载(overload): ①权限修饰符(public private 默认): 无关 ②返回值类型: ...
- offset() 方法 文档偏移量
以前看视频学习听到这个offset()感觉很陌生,没有用过,马上记到笔记里了,今天翻起笔记再次看到,都已经忘记是怎么用的了,所以来到这里狠狠的记下来: offset() 方法返回得或设置元素相对于文档 ...
- 将电脑特定文件夹保存在U盘中
为什么 各种网盘,借着国家扫黄的阶梯,纷纷取消自己的网盘的服务.但自己有一些不是很大,但又很重要的东西,比如说代码(虽然学的渣) 怎么做 再网上百度,有一些将U盘的文件偷偷拷到电脑的脚本,改一下复制文 ...
- 06《UML大战需求分析》之六
不知不觉中,大多数课程的学习已经接近了尾声,<UML大战需求分析>这本书也陪伴了我们很久.在学习的过程中,我发现很多课程中其实都离不开UML.足以证明,UML在需求分析中的重大作用和在我们 ...
- MongoDB 学习笔记(二):shell中执行增删查改
一.查 1.查询集合中所有文档:db.集合名.find(). 2.查询集合中第一个文档:db.集合名.findOne(). 3.指定查询条件:第一个参数就是指定查询条件 查询全部文档:db.集合名.f ...
- BZOJ 1264: [AHOI2006]基因匹配Match DP_树状数组_LCS转LIS
由于有重复数字,我们以一个序列为基准,另一个序列以第一个序列每个数所在下标为这个序列每个数对应的值. 注意的是,拆值的时候按照在第一个序列中的位置从大到小排,强制只能选一个. 最后跑一边最长上升子序列 ...