1.把rtsp视频流转化为图片传到云端
import _pickle as cPickle
import gc
import sys
import threading
import cv2
import json
import time
import requests
import base64
def push_image(source, id):
url = "云端地址"
headers = {"content-type": "application/json; charset=UTF-8"}
for image in LoadStreams(source):
try:
image = cv2.resize(image[0], (640, 480), interpolation=cv2.INTER_LINEAR)
image = cv2.imencode(".jpg", image)[1].tostring()
image = base64.b64encode(image)
print(sys.getsizeof(image))
with open("test.txt", "w") as f:
f.write(str(image))
id = id
pyload = {
"image": str(image),
"id": id
}
# print(task_id)
json_str_data = json.dumps(pyload)
response = requests.post(url, headers=headers, data=json_str_data)
print("response is:", response.text)
except:
continue
finally:
gc.collect()
class LoadStreams: # multiple RTSP tasks
def __init__(self, sources):
self.sources = [sources]
self.imgs = [None] * len(self.sources)
for i, s in enumerate(self.sources):
self.cap = cv2.VideoCapture(s)
w = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = self.cap.get(cv2.CAP_PROP_FPS) % 100
_, self.imgs[i] = self.cap.read() # guarantee first frame
thread = threading.Thread(target=self.update, args=([self.cap, i]), daemon=True)
print(' success (%gx%g at %.2f FPS).' % (w, h, fps))
thread.start()
print('') # newline
def update(self, cap, index):
n = 0
while cap.isOpened():
n += 1
cap.grab()
if n == 5:
_, self.imgs[index] = cap.retrieve()
n = 0
time.sleep(0.01) # wait time
def __del__(self):
self.cap.release()
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
img = self.imgs.copy()
if cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
return img
def __len__(self):
return 0
#
if __name__ == '__main__':
path = "rtsp://用户名:密码@ip/h264/ch1/main/av_stream"
push_image(path, "1")
2.云端服务器显示实时视频流
import base64
from flask import Flask, render_template, Response, request
import gc
app = Flask(__name__)
rtsp_frame = {}
def gen(id):
while True:
try:
frame = rtsp_frame[id]
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
except:
continue
finally:
gc.collect()
@app.route('/video_feed/<id>') # 该地址返回视频流响应
def video_feed(id):
return Response(gen(id),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route("/image", methods=["POST"])
def image():
data = request.get_json()
image_str = data["image"]
image_byte = eval(image_str)
image_arr = base64.b64decode(image_byte)
id = data["id"]
rtsp_frame[id] = image_arr
return "connect successful"
if __name__ == '__main__':
app.run(host='云端服务器ip', port=40001, threaded=True)