1 function [Y,U,V] = readYUV420file(filename, width, height) 2 % [Y,U,V] = readYUVfile(filename, width, height) 3 4 fid = fopen(filename,'rb'); 5 if fid==-1 6 error(['Cannot open file ' filename]); 7 end 8 9 % Number of pixels per image 10 nPx=width*height; 11 12 % nPx bytes luminance, nPx/4 bytes U, nPx/4 bytes V 13 frameSizeBytes = nPx*1.5; 14 15 % calculate number of frames 16 fseek(fid,0,'eof'); % move to end of file 17 fileLen=ftell(fid); % number of bytes 18 fseek(fid,0,'bof'); % rewind to start 19 20 % calculate number of frames 21 numFrames = floor(fileLen/frameSizeBytes); 22 23 Y=uint8(zeros(height,width,numFrames)); 24 U=uint8(zeros(height/2,width/2,numFrames)); 25 V=uint8(zeros(height/2,width/2,numFrames)); 26 27 [X,nBytes]=fread(fid, frameSizeBytes, 'uchar'); 28 29 for k=1:numFrames 30 31 % Store luminance 32 Y(:,:,k)=uint8(reshape(X(1:nPx), width, height).'); 33 34 % Store U channel 35 U(:,:,k)=uint8(reshape(X(nPx + (1:nPx/4)), width/2, height/2).'); 36 37 % Store V channel 38 V(:,:,k)=uint8(reshape(X(nPx + nPx/4 + (1:nPx/4)), width/2, height/2).'); 39 40 % Read next frame 41 [X,nBytes]=fread(fid, frameSizeBytes, 'uchar'); 42 end 43 44 45 fclose(fid); 46