⽤python实现监控视频⼈数统计
⽬录
⼀、图⽰
⼆、准备
三、⼀个简单服务器应⽤
四、向服务器发送图⽚
五、最终关键yolov5调⽤代码:
⼀、图⽰
客户端请求输⼊⼀段视频或者⼀个视频流,输出⼈数或其他⽬标数量,上报给上层服务器端,即提供⼀个http API调⽤算法统计出⼈数,最终http上报总⼈数
⼆、准备
相关技术 python pytorch opencv http协议 post请求
Flask
Flask是⼀个Python实现web开发的微框架,对于像我对web框架不熟悉的⼈来说还是⽐较容易上⼿的。
Flask安装
sudo pip install Flask
三、⼀个简单服务器应⽤
为了稍微了解⼀下flask是如何使⽤的,先做⼀个简单的服务器例⼦。
第⼀个⽂件hello.py。
from flask import Flask
app = Flask(__name__)
@ute("/")
def hello():
return 'hello world!'
@ute("/python")
def hello_python():
return 'hello python!'
if __name__ == '__main__':
app.run(host='0.0.0.0')
app.run(host=‘0.0.0.0')表⽰现在设定的ip为0.0.0.0,并且设定为0.0.0.0是⾮常⽅便的,如果你是在⼀
台远程电脑上设置服务器,并且那台远程电脑的ip是172.1.1.1,那么在本地的电脑上可以设定ip为172.1.1.1来向服务器发起请求。
第⼆个⽂件是request.py
import requests
url = '0.0.0.0:5000/'
r = (url)
print(r.status_code)
)
url = '0.0.0.0:5000/python'
r = (url)
print(r.status_code)
)
四、向服务器发送图⽚
服务器代码
#coding:utf-8
from flask import request, Flask
import os
app = Flask(__name__)
@ute("/", methods=['POST'])
def get_frame():
upload_file = request.files['file']
old_file_name = upload_file.filename
file_path = os.path.join('/local/share/DeepLearning', 'new' + old_file_name)
学python看谁的视频比较好
if upload_file:
upload_file.save(file_path)
print "success"
return 'success'
else:
return 'failed'
if __name__ == "__main__":
app.run("0.0.0.0", port=5000)
客户端代码
import requests
url = "0.0.0.0:5000"
filepath='./t2.jpg'
split_path = filepath.split('/')
filename = split_path[-1]
print(filename)
file = open(filepath, 'rb')
files = {'file':(filename, file, 'image/jpg')}
r = requests.post(url,files = files)
result = r.text
print result
这种情况长传图⽚是最快的,⽐⽤opencv先打开后传递象素级的数字要快很多.
五、最终关键yolov5调⽤代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/2/20 18:19
# @Author : xiaorun
# @Site :
# @File : yoloDetect.py
# @Software: PyCharm
import sys
import threading
from threading import Thread
import time
import os
import cv2
from yolo import YOLO5
import json,jsonify
import requests
import flask
from flask import request
headers = {'Content-Type': 'application/json'}
url_addr="123.206.106.55:8065/api/video/getPersonNum/"
# 创建⼀个服务,把当前这个python⽂件当做⼀个服务
server = flask.Flask(__name__)
server.debug = True
def gen_detector(url_video):
yolo = YOLO5()
opt = parseData()
yolo.set_config(opt.weights, opt.device, opt.img_size, f_thres, opt.iou_thres, True)
yolo.load_model()
camera = cv2.VideoCapture(url_video)
# 读取视频的fps, ⼤⼩
fps = (cv2.CAP_PROP_FPS)
size = ((cv2.CAP_PROP_FRAME_WIDTH), (cv2.CAP_PROP_FRAME_HEIGHT)) print("fps: {}\nsize: {}".format(fps, size))
# 读取视频时长(帧总数)
total = (cv2.CAP_PROP_FRAME_COUNT))
print("[INFO] {} total frames in video".format(total))
ret, frame = ad()
if ret==False:
video_parameter = {"accessKey": "1C7C48F44A3940EBBAQXTC736BF6530342",
"code": "0000",
"personNum": "video problem.."}
response = requests.post(url=url_addr, headers=headers, data=json.dumps(video_parameter))
print(response.json())
max_person=0
while total>0:
total=total-1
ret,ad()
if ret == True:
objs = yolo.obj_detect(frame)
if max_person<=len(objs):
max_person=len(objs)
for obj in objs:
cls = obj["class"]
cor = obj["color"]
conf = '%.2f' % obj["confidence"]
label = cls + " "
x, y, w, h = obj["x"], obj["y"], obj["w"], obj["h"]
cv2.putText(frame, label, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, cor, thickness=2)
person = "there are {} person ".format(len(objs))
cv2.putText(frame, person, (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), thickness=3)
video_parameter = {"accessKey": "1C7C48F44A3940EBBAQXTC736BF6530342",
"code": "0000",
"personNum": str(max_person)}
if total==0:
response = requests.post(url=url_addr, headers=headers, data=json.dumps(video_parameter))
print(response.json())
cv2.imshow("test",frame)
if cv2.waitKey(1)==ord("q"):
break
@ute('/video', methods=['post'])
def get_video():
if not request.data: # 检测是否有数据
return ('fail..')
video_name= request.data.decode('utf-8')
# 获取到POST过来的数据,因为我这⾥传过来的数据需要转换⼀下编码。根据晶具体情况⽽定
video_json = json.loads(video_name)
print(video_json)
accessKey=video_json["accessKey"]
if accessKey=="1C7C48F44A3940EBBAQXTC736BF6530342":
code=video_json["code"]
url_video=video_json["url"]
print(url_video)
gen_detector(url_video)
# 把区获取到的数据转为JSON格式。
data_return={"code":200,"data":url_video,"message":"请求成功","sucsess":"true"}
return json.dumps(data_return)
else:
pass
# 返回JSON数据。
if __name__ == '__main__':
server.run(host='192.168.1.250', port=8888)
客户端请求测试:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/5/12 15:12
# @Author : xiaorun
# @Site :
# @File : test_post.py
# @Software: PyCharm
import requests,json
headers = {'Content-Type': 'application/json'}
user_info = {"accessKey":"1C7C48F44A3940EBBAQXTC736BF6530342",
"code":"N000001",
"url":"http:xxxx/video/xxxx.mp4"
}
r = requests.post("8.8.9.76:8888/video",headers=headers, data=json.dumps(user_info))
print (r.text)
到此这篇关于⽤python实现监控视频⼈数统计的⽂章就介绍到这了,更多相关python视频⼈数统计内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论