现在的位置: 首页 > 综合 > 正文

Convert Avi to Yuv420 matlab code

2013年05月25日 ⁄ 综合 ⁄ 共 1903字 ⁄ 字号 评论关闭

%# Get the video data:
clear all;
close all;
fclose all;
vidObj = VIDEOREADER('D:\myTools\person01_walking_d1_uncomp.avi'); %mmreader # Create a video file object daria_bend.avi'); %

nFrames = vidObj.NumberOfFrames; %# Get the number of frames
vidHeight = vidObj.Height; %# Gdaria_bend.avi'); %
vidWidth = vidObj.Width; %# Get the image width

%# Preallocate the structure array of movie frames:

mov(1:nFrames) = struct('cdata',zeros(vidHeight,vidWidth,3,'uint8'),...
'colormap',[]); %# Note that colormap is empty!

%# Read each video frame into the structure array:

for k = 1:nFrames
mov(k).cdata = read(vidObj,k); %# Place frame k in the cdata field of mov(k)
end

%# Save the movie frame array as a YUV 4:2:0 file:

saveFileYuv(mov,'D:\myTools\myVideo1.yuv',1);

saveFileYuv.m:

function saveFileYuv(mov, fileName, mode)
% save RGB movie [0, 255] to YUV 4:2:0 file

switch mode
case 1 % replace file
fileId = fopen(fileName, 'w');
case 2 % append to file
fileId = fopen(fileName, 'a');
otherwise
fileId = fopen(fileName, 'w');
end

dim = size(mov(1).cdata);
nrFrame = length(mov);

for f = 1 : 1 : nrFrame
imgRgb = frame2im(mov(f));

% convert YUV to RGB
imgYuv = reshape(convertRgbToYuv(reshape(imgRgb, dim(1) * dim(2), 3)), dim(1), dim(2), 3);
%imgYuv = reshape(rgb2ycbcr(uint8(reshape(imgRgb, dim(1) * dim(2), 3))), dim(1), dim(2), 3);

% write Y component
buf = reshape(imgYuv(:, :, 1).', [], 1); % reshape
count = fwrite(fileId, buf, 'uchar');

% write U component
buf = reshape(imgYuv(1 : 2 : end, 1 : 2 : end, 2).', [], 1); % downsample and reshape
count = fwrite(fileId, buf, 'uchar');

% write V component
buf = reshape(imgYuv(1 : 2 : end, 1 : 2 : end, 3).', [], 1); % downsample and reshape
count = fwrite(fileId, buf, 'uchar');
end

fclose(fileId);

ConvertRgbToYuv.m:

function yuv = ConvertRgbToYuv(rgbUint8)
[mn, c] = size(rgbUint8);
rgb = double(rgbUint8); %very important; If not convert uint8 to double, -0.1687*rgb(:, 1) will always be zero

yuv = uint8(zeros(mn, 3));

yuv(:, 1) = min(255,max(0,0.299*rgb(:, 1) + 0.587*rgb(:, 2) + 0.114*rgb(:, 3)));
yuv(:, 2) = min(255,max(0,-0.1687*rgb(:, 1) -0.3313*rgb(:, 2) + 0.5*rgb(:, 3) + 128));
yuv(:, 3) = min(255,max(0,0.5*rgb(:, 1) -0.4187*rgb(:, 2) -0.0813*rgb(:, 3) + 128));
end

【上篇】
【下篇】

抱歉!评论已关闭.