ffmepg

[TOC]

FFmpeg

ffmpeg也可以读取文件和从设备中读取视频信号,还可以从多个音视频文件中读取,然后输出多个音视频文件。

centos

1
2
3
4
5
6
yum install ffmpeg
# centos系统自带的ffmpeg一般都是 2.x的版本,很难满足现在很多需求,可以添加其他第三方源来安装,或者编译安装。
yum install yum-utils
yum-config-manager --add-repo https://negativo17.org/repos/epel-multimedia.repo
yum remove libva1-1.3.1-11.el7.x86_64
yum install ffmpeg

ubuntu

1
sudo apt install ffmpeg

conda

1
2
# conda安装的ffmpeg值存在于当前env环境中。
conda install ffmpeg

语法格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ffmpeg [global_options] {[input_file_options] -i input_url} ... {[output_file_options] output_url} ...

# 从视频文件读取
-i test.avi

# 从设备读取
-i /dev/video0

# 从视频流读取
-i rtsp://your_ip:port/

# 设置尺寸
-s 640*480

# 输出为文件,直接在后面写出文件名即可
ffmpeg -f video4linux -r 10 -i /dev/video0 test.asf

# 输出到视频流
ffmpeg -i /dev/video0 -f mpegts -codec:v mpeg1video http://localhost:8081/supersecret

ffmpeg功能强大,参数巨多。详情请看ffmpeg官方文档

常见实用命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 把图片合成转成视频
ffmpeg -y -r 24 -i rfcn/00%4d.JPEG -vcodec libx264 rfcn.mp4

# 把视频转成图片
ffmpeg -i 1.mp4 test/%6d.JPEG

# 格式转换
ffmpeg animals.avi animals.mp4

# 保留音频
ffmpeg -i animals.mp4 animals.mp3

# 合成音视频
ffmpeg -i animals.mp4 -i animals.mp3 animals_combine.mp4

$ cat file.list
file 'test1.mp4'
file 'test1.mp4'
file 'test1.mp4'
ffmpeg -f concat -i file.list -c copy test.mp4


# 截取视频 (从162秒开始截取30秒)
ffmpeg -ss 162 -t 30 -i animals_ori.mp4 face.mp4

FFmpeg + Opencv

ffmpeg还可以从管道pipe作为输入,或者输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# opencv获取视频,然后通过pipe管道传入ffmpeg的输入,再通过ts流输出到远程页面
# 中间可以加上预测结果,这样网页上显示的就是预测的结果
import subprocess
import cv2

video_capture = cv2.VideoCapture(0)
cmd = 'ffmpeg -f rawvideo -vcodec rawvideo -pixel_format bgr24 -video_size 640x480 -i pipe:0 -f mpegts -codec:v mpeg1video -s 512x512 -bf 0 http://localhost:8081/supersecret'.split()
converter = subprocess.Popen(cmd, stdin=subprocess.PIPE)
while True:
_, frame = video_capture.read()
# 在这里,可以对获取到的frame进行预测处理
# frame = predict(frame)
byte_frame = frame.tostring()
converter.stdin.write(byte_frame)
cv2.imshow("image", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break