Main Content

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

イメージ シーケンスとビデオとの間の変換

この例では、VideoReaderVideoWriter を使用して、ビデオ ファイルとイメージ ファイルのシーケンスとの間で変換する方法を示します。

サンプル ファイル shuttle.avi には、121 枚のフレームが含まれています。VideoReaderおよび関数imwriteを使用し、これらのフレームをイメージ ファイルに変換します。次に、VideoWriterを使用して、このイメージ ファイルを AVI ファイルに変換します。

設定

イメージ シーケンスを保存するための一時作業フォルダーを作成します。

workingDir = tempname;
mkdir(workingDir)
mkdir(workingDir,"images")

VideoReader オブジェクトの作成

サンプル ファイルからのフレームの読み取りに使用する VideoReader オブジェクトを作成します。

shuttleVideo = VideoReader("shuttle.avi");

イメージ シーケンスの作成

ビデオ内をループして、img という名前の幅 x 高さ x 3 の配列に各フレームを読み取ります。N.jpg という形式の名前をもつ JPEG ファイルに各イメージを書き込みます。N は 3 桁のフレーム番号です。

i = 1;

while hasFrame(shuttleVideo)
   img = readFrame(shuttleVideo);
   filename = sprintf("%03d",i)+".jpg";
   fullname = fullfile(workingDir,"images",filename);
   imwrite(img,fullname)    % Write to a JPEG file (001.jpg, 002.jpg, ..., 121.jpg)
   i = i+1;
end

イメージ ファイル名の検索

images フォルダーにあるすべての JPEG ファイルの名前を検索します。イメージ名のセットを cell 配列に変換します。

imageNames = dir(fullfile(workingDir,"images","*.jpg"));
imageNames = {imageNames.name}';

イメージ シーケンスによる新しいビデオの作成

既定で Motion-JPEG AVI ファイルを作成する VideoWriter オブジェクトを作成します。

outputVideo = VideoWriter(fullfile(workingDir,"shuttle_out.avi"));
outputVideo.FrameRate = shuttleVideo.FrameRate;
open(outputVideo)

イメージ シーケンス内で繰り返し、各イメージを読み取り、それをビデオに書き込みます。

for i = 1:length(imageNames)
   img = imread(fullfile(workingDir,"images",imageNames{i}));
   writeVideo(outputVideo,img)
end

ビデオ ファイルを完成します。

close(outputVideo)

最終的なビデオの表示

VideoReader オブジェクトを作成します。

shuttleAvi = VideoReader(fullfile(workingDir,"shuttle_out.avi"));

ビデオ フレームから構造体配列を作成します。

i = 1;
while hasFrame(shuttleAvi)
   mov(i) = im2frame(readFrame(shuttleAvi));
   i = i+1;
end

ビデオの幅と高さに基づいて Figure のサイズを設定し、ビデオを 1 回再生します。

vf = figure(Position=[0 0 shuttleAvi.Width shuttleAvi.Height]);
imshow(mov(1).cdata,Border="tight")
movie(vf,mov,1,shuttleAvi.FrameRate)

Figure contains an axes object. The axes object contains an object of type image.

VideoReader オブジェクトのクリア

VideoReader オブジェクトをクリアします。

clear shuttleVideo shuttleAvi

著作権表示

スペースシャトルの動画はNASAによって提供されています。

関連するトピック

ビデオ ファイルの読み取り