编写一个Python程序,
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
编写python程序,实现调用yolo v3,检测图片中的车辆。
具体代码如下:
from __future__ import division, print_function
from flask import Flask, request
import base64
import numpy as np
import cv2
import tensorflow as tf
import argparse
import time
import os
from utils.misc_utils import parse_anchors, read_class_names
from utils.nms_utils import gpu_nms
from utils.plot_utils import get_color_table, plot_one_box
from utils.data_aug import letterbox_resize
from model import yolov3
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # 这一行注释掉就是使用Gpu,不注释就是使用cpu
parser = argparse.ArgumentParser(description="YOLO-V3 video test procedure.")
parser.add_argument("--anchor_path", type=str, default="./data/yolo_anchors.txt",
help="The path of the anchor txt file.")
parser.add_argument("--new_size", nargs='*', type=int, default=[416, 416],
help="Resize the input image with `new_size`, size format: [width, height]")
parser.add_argument("--letterbox_resize", type=lambda x: (str(x).lower() == 'true'), default=True,
help="Whether to use the letterbox resize.")
parser.add_argument("--class_name_path", type=str, default="./data/s",
help="The path of the class names.")
parser.add_argument("--restore_path", type=str, default="./data/darknet_weights/yolov3.ckpt",
help="The path of the weights to restore.")
args = parser.parse_args()
args.anchors = parse_anchors(args.anchor_path)
args.classes = read_class_names(args.class_name_path)
args.num_class = len(args.classes)
color_table = get_color_table(args.num_class)
sess=tf.Session()
input_data = tf.placeholder(tf.float32, [1, args.new_size[1], args.new_size[0], 3],
name='input_data')
yolo_model = yolov3(args.num_class, args.anchors)
with tf.variable_scope('yolov3'):
pred_feature_maps = yolo_model.forward(input_data, False)
pred_boxes, pred_confs, pred_probs = yolo_model.predict(pred_feature_maps)
pred_scores = pred_confs * pred_probs
boxes, scores, labels = gpu_nms(pred_boxes, pred_scores, args.num_class, max_boxes=200, score_thresh=0.3, nms_thresh=0.45)
saver = tf.train.Saver()
saver.restore(sess, args.restore_path)
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello! Service running...'
@app.route('/detect/', methods=['POST'])
def detect():
#print(request.headers)
#print(request.args)
#print(request.form)
#print(request.form['data1'])
#print(request.form.get('data1'))
#print(request.form.getlist('data1'))
#print(request.form['img'])
#img_ori = open(r'./data/demo_data/image3.jpg','rb')
#img_ori = cv2.imread("./data/demo_data/image3.jpg")
#img_b64encode=base64.b64encode(img_ori.read())
#print(img_b64encode)
img_b64encode=bytes(request.form['img'], encoding = "utf-8")
img_b64decode = base64.b64decode(img_b64encode) # base64解码
img_array = np.fromstring(img_b64decode,np.uint8) # 转换np序列
img_ori=cv2.imdecode(img_array,cv2.COLOR_BGR2RGB) # 转换Opencv格式
#cv2.imwrite('received.jpg', img_ori)
if args.letterbox_resize:
img, resize_ratio, dw, dh = letterbox_resize(img_ori, args.new_size[0], args.new_size[1])
else:
height_ori, width_ori = img_ori.shape[:2]
img = cv2.resize(img_ori, tuple(args.new_size))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = np.asarray(img, np.float32)
img = img[np.newaxis, :] / 255.
#start_time = time.time()
boxes_, scores_, labels_ = sess.run([boxes, scores, labels], feed_dict={input_data: img})
#end_time = time.time()
#delta = end_time - start_time
#print ("识别图片用时秒:"+str(delta))
# rescale the coordinates to the original image
if args.letterbox_resize:
boxes_[:, [0, 2]] = (boxes_[:, [0, 2]] - dw) / resize_ratio
boxes_[:, [1, 3]] = (boxes_[:, [1, 3]] - dh) / resize_ratio
else:
boxes_[:, [0, 2]] *= (width_ori/float(args.new_size[0]))
boxes_[:, [1, 3]] *= (height_ori/float(args.new_size[1]))
jsonstr1="{\"results\":[";
jsonstr2="";
jsonstr3="]}";
for i in range(len(boxes_)):
x0, y0, x1, y1 = boxes_[i]
jsonstr2=jsonstr2+',{"xmin":'+str(x0)+',"ymin":'+str(y0)+',"xmax":'+str(x1)+',"ymax":'+str(y1)+',"sc ore":'+'{:.2f}'.format(scores_[i] * 100)+',"classname":"'+ args.classes[labels_[i]]+'"}'
plot_one_box(img_ori, [x0, y0, x1, y1], label=args.classes[labels_[i]] + ', {:.2f}%'.format(scores_[i] * 100), color=color_table[labels_[i]])
jsonstr=jsonstr1+jsonstr2[1:]+jsonstr3
#cv2.putText(img_ori, '{:.2f}ms'.format((end_time - start_time) * 1000), (40, 40), 0,
#fontScale=1, color=(0, 255, 0), thickness=2)
#cv2.imshow('image', img_ori)
#cv2.imwrite('detection_result.jpg', img_ori)
#cv2.waitKey(0)
return jsonstr
if __name__ == '__main__':
app.run(port=8888,debug=True)。