我正在尝试使用skvideo.io.FFmpegWriter
和cv2.VideoCapture
来精细控制动态捕捉的相机图像帧的视频编码,例如
from skvideo import io
import cv2
fps = 60
stream = cv2.VideoCapture(0) # 0 is for /dev/video0
print("fps: {}".format(stream.set(cv2.CAP_PROP_FPS, fps)))
stream.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
print("bit_depth: {}".format(stream.set(cv2.CAP_PROP_FORMAT, cv2.CV_8U)))
video = io.FFmpegWriter('/tmp/test_ffmpeg.avi',
inputdict={'-r': fps, '-width': 1920, '-height': 1080},
outputdict={'-r': fps, '-vcodec': 'libx264', '-pix_fmt': 'h264'}
)
try:
for i in range(fps*10): # 10s of video
ret, frame = stream.read()
video.writeFrame(frame)
finally:
stream.release()
try:
video.close()
except:
pass
但是,我收到以下异常(在Jupyter笔记本中):
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-33-007a547c4229> in <module>()
18 while range(fps*10):
19 ret, frame = stream.read()
---> 20 video.writeFrame(frame)
21 except BaseException as err:
22 raise err
/usr/local/lib/python3.6/site-packages/skvideo/io/ffmpeg.py in writeFrame(self, im)
446 T, M, N, C = vid.shape
447 if not self.warmStarted:
--> 448 self._warmStart(M, N, C)
449
450 # Ensure that ndarray image is in uint8
/usr/local/lib/python3.6/site-packages/skvideo/io/ffmpeg.py in _warmStart(self, M, N, C)
412 cmd = [_FFMPEG_PATH + "/" + _FFMPEG_APPLICATION, "-y"] + iargs + ["-i", "-"] + oargs + [self._filename]
413
--> 414 self._cmd = " ".join(cmd)
415
416 # Launch process
TypeError: sequence item 3: expected str instance, int found
将其更改为video.writeFrame(frame.tostring())
会导致ValueError: Improper data input
,这让我很困惑。
我应该如何将每个帧(由OpenCV返回)写入FFmpegWriter实例?
如果我从inputdict
调用中删除outputdict
和io.FFmpegWriter
,则代码可以正常工作,但是由于我需要对视频编码进行精细控制,因此这对我来说是无效的(我正在尝试对从相机捕获的原始视频进行无损/近无损压缩,并尝试在压缩与保真度方面建立最佳折衷方案。
答案 0 :(得分:4)
这里需要注意的几点:
skvideo.io.FFmpegWriter
使用ffmpeg
命令行工具编码视频,而不是C API。因此,请首先在终端中测试ffmpeg
命令,以确保您的管道正常运行。inputdict={},outputdict={}
接受字符串输入,而不是整数。如果您有整数变量,请使用str(var_name)
将其转换为字符串。pix_fmt
。要获取所有pix_fmt
的列表,请使用ffmpeg -pix_fmts
。请记住,x264
不接受pix_fmt
内部支持的所有ffmpeg
。因此,对于近乎无损的编码(请参见this和this),我们可以使用以下命令:
ffmpeg -s 1920x1080 -r 60 -i /dev/video0 -s 1920x1080 -r 60 -c:v libx264 -crf 17 -preset ultrafast -pix_fmt yuv444p test_ffmpeg.avi
翻译成skvideo.io.FFmpegWriter
的同一命令是:
fps = 60
width = 1920
height = 1080
crf = 17
video = io.FFmpegWriter('/tmp/test_ffmpeg.avi',
inputdict={'-r': str(fps), '-s':'{}x{}'.format(width,height)},
outputdict={'-r': str(fps), '-c:v': 'libx264', '-crf': str(crf), '-preset': 'ultrafast', '-pix_fmt': 'yuv444p'}
)