我正在开发一个Python模块,使用OpenCV连接到一个RTSP流来对视频进行一些预处理(主要是降低fps和分辨率),然后将其存储在文件系统中。但是,即使尝试了多个编解码器,查找了类似的开发...我总是得到一个空的视频。我看到了这个线程(cv::VideoWriter yields unreadable video),可能类似,但是它是用C++开发的。有没有人处理过这个问题?我通常使用样本RTSP流作为参考,例如rtsp://freja.hiof.no:1935/rtplive/definst/hessdalen03.stream,并且可以正确地从VLC接收并观看流。我看到了很多讨论如何从RTSP流中捕获视频,或者如何使用VideoWriters和VideoReaders类和视频文件,但几乎没有结合两者的东西。任何帮助都将不胜感激 :) 谢谢!!
编辑1:用于存储帧的示例代码。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy
# Test frame.
width, height = 400, 300
width_2, height_2 = int(width / 2), int(height / 2)
frame = numpy.zeros((height, width, 3), numpy.uint8)
cv2.rectangle(frame, (0, 0), (width_2, height_2), (255, 0, 0), cv2.FILLED)
cv2.rectangle(frame, (width_2, height_2), (width, height), (0, 255, 0), cv2.FILLED)
frames = [frame for _ in range(100)]
fps = 25
# Define the codec.
#fourcc = cv2.VideoWriter_fourcc(*'X264')
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
# Create VideoWriter object
out = cv2.VideoWriter(filename='video.avi',
fourcc=fourcc,
apiPreference=cv2.CAP_FFMPEG,
fps=float(fps),
frameSize=(width, height),
isColor=True)
result = 0
for frame in frames:
result += 0 if out.write(frame) is None else 1
print(result)
out.release()
编辑2: 解决方案
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy
# Test frame.
width, height = 400, 300
width_2, height_2 = int(width / 2), int(height / 2)
frame1 = numpy.zeros((height, width, 3), numpy.uint8)
cv2.rectangle(frame1, (0, 0), (width_2, height_2), (255, 0, 0), cv2.FILLED)
cv2.rectangle(frame1, (width_2, height_2), (width, height), (0, 255, 0), cv2.FILLED)
cv2.imwrite('frame1.jpg', frame1)
frame2 = numpy.zeros((height, width, 3), numpy.uint8)
cv2.rectangle(frame2, (width_2, 0), (width, height_2), (255, 0, 0), cv2.FILLED)
cv2.rectangle(frame2, (0, height_2), (width_2, height), (0, 255, 0), cv2.FILLED)
cv2.imwrite('frame2.jpg', frame2)
range1 = [frame1 for _ in range(10)]
range2 = [frame2 for _ in range(10)]
frames = range1 + range2 + range1 + range2 + range1
fps = 2
# Define the codec.
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
# Create VideoWriter object
out = cv2.VideoWriter('video.avi', fourcc, float(fps), (width, height))
for frame in frames:
out.write(frame)
out.release()