import time
import cv2
import numpy as np
from ultralytics import YOLO
from flask import Flask, render_template, Response
app10 = Flask(__name__)
# Replace with your credentials and video stream URL
# Construct the RTSP URL with credentials
video_url = f"rtsp://{username}:{password}@{ip_address}:{port}" # rtsp地址
print(video_url, "----video_url----")
model = YOLO(r"D:\cvdata\data2\aikt\flask_video\main_yolo\best.pt")
def gen_frame():
# Open the video stream
cap = cv2.VideoCapture(video_url)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
# 设置视频流的超时
cap.set(cv2.CAP_PROP_BUFFERSIZE, 3)
while True:
# Read a frame from the video
retsu, frame = cap.read()
if not retsu:
print("Error: Could not read frame.")
time.sleep(3) # 缓存0.1s
continue
frame_size = cv2.resize(frame, (640, 480))
results = model(frame_size)
dection_frame = results[0].plot()
ret, buffer = cv2.imencode(".jpg", dection_frame)
dection_frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + dection_frame + b'\r\n') # 使用yield返回每一帧,适用于流式响应
@app10.route("/video_start")
def video_start():
return Response(gen_frame(), mimetype="multipart/x-mixed-replace; boundary=frame")
@app10.route("/")
def index():
return render_template("index.html")
if __name__ == '__main__':
app10.run(host="0.0.0.0", port=5000, debug=True)
最近在做接入视频流有关,遇到问题,代码接入视频流,有延迟,并且只能接入视频流50秒,就报错Error: Could not read frame.
有哪位大神,做过rtsp的经验,可以指导一下吗?B站上的资料鱼龙混杂,更多的是类似于我这种,求大佬救救我