在本地网络上使用 RTSP/RTP 和 FFMPEG 后端
这里是一些简单的步骤,可让您通过本地网络处理来自 Android 设备摄像头的帧。首先,我们需要下载一个可靠的 RTSP 服务器应用程序。为此,我选择的应用程序是 RTSP 摄像头服务器。
在 OpenCV 方面,VideoCapture 能够从流源中抓取帧。但是,我们需要将流后端参数传递给构造函数。为此,您可以使用多种选项,但在可能的解决方案中,我更喜欢 FFMPEG 后端,因为它是交叉引用。
幸运的是,PyPi 上提供的预构建 OpenCV Python随 FFMPEG 一起提供。通过以下 pip 安装设置 OpenCV 依赖项后:
pip install opencv-python
我们可以开始使用RTSP流。
import cv2
# Set RTSP Transport Protocol to UDP
import os
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
cap = cv2.VideoCapture("rtsp://DE.VI.CE.IP:5554/camera", cv2.CAP_FFMPEG)
while True:
ret, frame = cap.read()
if not ret:
print("Empty frame") # absl-py logging would be better
# time.sleep(0.1) # You may sleep and try again
continue
cv2.imshow("RTSP Stream", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
或者我们可以通过 VideoWriter 将帧保存到文件中:
import cv2
# Set RTSP Transport Protocol to UDP
import os
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
cap = cv2.VideoCapture("rtsp://192.168.2.166:5554/camera", cv2.CAP_FFMPEG)
# Set output frame height and width
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# Set playback FPS to 24
fps = 24
fourcc = cv2.VideoWriter_fourcc("X", "V", "I", "D")
writer = cv2.VideoWriter("out.avi", fourcc, fps, (width, height))
while True:
ret, frame = cap.read()
if not ret:
print("Empty frame") # absl-py logging would be better
# time.sleep(0.1) # You may sleep and try again
continue
writer.write(frame)
cv2.imshow("RTSP Stream", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Clean-up
cap.release()
writer.release()
cv2.destroyAllWindows()
感谢阅读。
1万+

被折叠的 条评论
为什么被折叠?



