我有连接到 rtsp 摄像头的代码:
from flask import Flask, Response
import cv2
app = Flask(__name__)
RTSP_URL = "rtsp://admin:[email protected]:554/onvif1"
def generate_frames():
cap = cv2.VideoCapture(RTSP_URL)
frame_skip = 2 # Skip every 2 frames
while True:
for _ in range(frame_skip):
cap.read() # Skip frames
success, frame = cap.read()
if not success:
break
else:
# Resize frame to lower resolution
frame = cv2.resize(frame, (320, 240)) # Reduce to 320x240 resolution
# Encode frame to JPEG format with lower quality
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 30] # Set JPEG quality to 30
_, buffer = cv2.imencode('.jpg', frame, encode_param)
frame = buffer.tobytes()
# Yield frame in MJPEG format
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/video_feed')
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
它在我的本地电脑上工作正常,即使相机和电脑位于不同的网络中(我使用ubuntu桌面),但我购买了一个ubuntu服务器并使用了相同的代码,我通过以下方式打开了烧瓶:http://x.x.x.x:5000 /video_feed 这就是 ubuntu 服务器的 ip,即使我对 librareis 进行了相同的安装,它也非常慢,而且服务器的硬件比我的 ubuntu 桌面强得多,我降低了分辨率,它的工作效果好一点但它仍然非常非常慢。 ubuntu 服务器比我的 ubuntu 桌面有更好的连接,正如我告诉你的,它有 rtx 4090 24gb 和 100gb 内存,所以它不适合来自 rtsp 摄像头的视频流
试试这个
from flask import Flask, Response
import cv2
app = Flask(__name__)
RTSP_URL = "rtsp://admin:[email protected]:554/onvif1"
def generate_frames():
cap = cv2.VideoCapture(f'ffmpeg -hwaccel cuda -i {RTSP_URL} -f rawvideo -pix_fmt bgr24 -an pipe:1', cv2.CAP_FFMPEG)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # Adjust buffer size if needed
frame_skip = 2 # Skip every 2 frames
while True:
for _ in range(frame_skip):
cap.read() # Skip frames
success, frame = cap.read()
if not success:
break
else:
frame = cv2.resize(frame, (320, 240)) # Reduce resolution
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 30] # Lower JPEG quality
_, buffer = cv2.imencode('.jpg', frame, encode_param)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/video_feed')
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)