MATLAB 視訊與影象轉換
阿新 • • 發佈:2019-02-09
本節主要講解一下如何使用MATLAB實現視訊轉換成幀圖片,以及幀圖片如何連線成視訊。
MATLAB將視訊轉換成幀圖片
我們將該過程分解成一下幾個步驟:- 讀取視訊,獲取視訊屬性。
- 取得視訊的每一幀圖片,並分別儲存。
對以上幾個需求MATLAB中都有函式可以滿足。
- 讀取視訊資訊,使用VideoReader函式
- 讀取每一幀圖片使用read函式,儲存圖片使用imwrite函式
%%將視訊轉換成幀圖片 clc; clear; %% 讀取視訊 video_path='video_test.avi'; video_obj=VideoReader(video_path); frame_number=video_obj.
下面我們就來詳細解釋一下我們在上述程式中使用的函式。
VideoReader
在MATLAB命令列輸入命令help VideoReader
顯示如下:VideoReader Create a multimedia reader object. OBJ = VideoReader(FILENAME) constructs a multimedia reader object, OBJ, that can read in video data from a multimedia file. FILENAME is
輸入
doc VideoReader
能夠看到更詳細的資訊,和VideoReader的屬性和方法。
這裡我調幾個比較重要的屬性講解一下。properties explain BitsPerPixel Bits per pixel of the video data. Duration Total length of the file in seconds. FrameRate Frame rate of the video in frames per second. Height Height of the video frame in pixels. Width Width of the video frame in pixels. Name Name of the file associated with the object. NumberOfFrames Total number of frames in the video stream.Some files store video at a variable frame rate, including many Windows Media Videofiles. For these files, VideoReader cannot determine the number of frames until you read the last frame. When you construct the object, VideoReader returns a warning and does not set the NumberOfFrames property.To count the number of frames in a variable frame rate file,use the read method to read the last frame of the file. For example: vidObj = VideoReader(‘varFrameRateFile.wmv’); lastFrame = read(vidObj, inf); numFrames = vidObj.NumberOfFrames; Path String containing the full path to the file associated with the reader. Tag String that identifies the object. Default: ” Type Class name of the object: ‘VideoReader’. UserData Generic field for data of any class that you want to add to the object.Default: []
MATLAB將幀圖片轉換成視訊
幀圖片轉換成視訊是視訊轉換成幀圖片的逆過程。framesPath = uigetdir('~/Desktop','please select image path');%影象序列所在路徑,同時要保證影象大小相同 videoName = './video/Bolt.avi';%表示將要建立的視訊檔案的名字 fps = 25; %幀率 startFrame = 1; %從哪一幀開始 endFrame = 490; %哪一幀結束 if(exist('./video/videoName','file')) delete ./video/videoName.avi end %生成視訊的引數設定 aviobj=VideoWriter(videoName); %建立一個avi視訊檔案物件,開始時其為空 aviobj.FrameRate=fps; open(aviobj);%Open file for writing video data %讀入圖片 for i=startFrame:endFrame fileName=sprintf('%d',i); fileName=strcat('im_',fileName); frames=imread([framesPath '/' fileName,'.jpg']); frames=im2frame(frames); %讀如frames變數的是圖片,這裡要將圖片轉換成幀儲存到變數frames中,這樣才能成功寫入幀到視訊物件中。 writeVideo(aviobj,frames); end close(aviobj);% 關閉建立視訊