首先来个简单的例子,使用FFMPEG打开视频文件,并解码保存成一张张的图片。
具体的步骤如下所示:
1.首先需要先初始化一下,使用如下函数:
1 |
|
使用这个函数完成编码器和解码器的初始化,只有初始化了编码器和解码器才能正常使用,否则会在打开编解码器的时候失败。
2.接着需要分配一个AVFormatContext,FFMPEG所有的操作都要通过这个AVFormatContext来进行
1 |
|
3.接着调用打开视频文件
这里文件名先不要使用中文,否则会打开失败,后期再讲解如何处理中文。
1 2 |
|
4.文件打开成功后就是查找文件中的视频流了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
5.现在根据视频流 打开一个解码器来解码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
可以看出 我们可以直接根据查找到的视频流信息获取到解码器。
而且我们并不知道他实际用的是什么编码器。
这就是为什么一开始我们使用FFMPEG来操作,因为很多东西我们可以不关系。
6.现在开始读取视频了:
1 2 3 4 5 6 7 8 |
|
可以看出 av_read_frame读取的是一帧视频,并存入一个AVPacket的结构中。
7.前面我们说过 视频里面的数据是经过编码压缩的,因此这里我们需要将其解码:
1 2 3 4 5 6 7 8 9 10 |
|
8.基本上所有解码器解码之后得到的图像数据都是YUV420的格式,而这里我们需要将其保存成图片文件,因此需要将得到的YUV420数据转换成RGB格式,转换格式也是直接使用FFMPEG来完成:
1 2 3 4 5 6 |
|
至于YUV420和RGB图像格式的具体内容,这里不用去了解。这里只需要知道有这么个东西就行了,对我们使用FFMPEG转换没有影响。
9.得到RGB数据之后就是直接写入文件了:
1 |
|
至此读取视频解码保存成图片就写好了:
完整的代码如下:
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
|