You are on page 1of 23

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011

ALL 2011 Basic Image Video Processing and Analysis

Matlab Tutorial - Image-Video Signal Processing and Analysis Lakis Christodoulou GOAL This lab experiments main goal is to show how we can perform basic image processing operations using our knowledge of matrices and MATLABs built-in support for reading and writing image files. REFERENCE Hanselman, D. and Littlefield, B. [2001]. Mastering MATLAB 6, Prentice Hall, Upper Saddle River, NJ. Chapters 27-28.

PROCEDURE 1. Start MATLAB. 2. Images in MATLAB consist of a data matrix and usually an associated colormap matrix. A colormap is an N x 3 array used to represent color values. Each row in a colormap represents an individual color, using numbers in the range 0 to 1. There are three types of image data matrices: indexed images, intensity images, and truecolor or RGB images. In this lab we will see at least one example of each. Lets start by loading the built-in indexed image clown. It will be stored in two files, X and map: load clown size(X) size(map) 3. Display the image using: image(X), colormap(map), axis image off 4. Inspect the R, G, and B contents of a particular pixel of coordinates [r,c]: r = 3; c = 45; map(X(r,c),:) 5. Explore the image and its colormap and report your most relevant findings. 6. Download the file lenna.gif (containing one of the most widely used test images in Digital Image Processing) from the Course Materials area of Blackboard and open it using: A = imread('lenna.gif','gif'); size(A) 7. Display it using: imagesc(A), colormap(gray), axis off 8. Repeat step 7 using: imshow(A) image(A) and report the differences. Question: Does the order matter? (Why?) 9. Display Lennas histogram: Ad = double(A) + 1; figure R = reshape(Ad,65536,1);

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
hist(R,256) 10. Apply a gamma correction transformation function (gamma = 0.5) to Lenna, and save the result to variable A2. 11. Display the result and the corresponding histogram. 12. Repeat steps 10 and 11 for a total of 5 values of gamma: 0.1, 0.5, 0.9, 1.5, and 2.5, storing the results in separate variables: A1, A5. 13. Display the original and the five gamma-corrected variations in one single window, using: subplot(2,3,1), imagesc(Ad), colormap(gray), axis off, title('Original') subplot(2,3,6), imagesc(A5), colormap(gray), axis off, title('Gamma = 2.5') 14. Requantize the Lenna image to 64, 16, 8, 4, and 2 gray levels, storing the results in separate variables (A64, A16, , A2), using: A64 = floor(Ad ./ 4); A2 = floor(Ad ./ 128); 15. Display the original and the five variations in one single window, using: subplot(2,3,1), imagesc(Ad), colormap(gray), axis off, title('Original') subplot(2,3,6), imagesc(A2), colormap(gray), axis off, title('2 gray levels') 16. Resample the Lenna image to 128 128, 64 64, and 16 16 pixels, storing the results in separate variables (S1, , S3). Question: How did you do it? 17. Display the original and the three variations in one single window. 18. Use some of the resulting images from above to perform image arithmetic and logic operations. Carefully inspect the results, both visually as well as checking representative values (e.g., max and min) and try to derive a general conclusion as to how MATLAB handles values outside the [0..Lmax] range of gray levels. 19. Load and display a truecolor image (Fig. 6.28, p. 313, from the textbook): B = imread('Fig6.28(a).jpg'); size (B) imshow(B) 20. Use the diary command to log everything you did (right) in this assignment into a file, lab3.txt. 21. Spend some time playing with functions and commands related to the scope of this assignment and log the most interesting results. 22. Write your conclusions and remarks and submit your report (in MSWord format, feel free to use this doc as a starting point) via Blackboard.

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
Section 0 Image-Video Processing and Analysis Useful functions: colormap(gray) To set the colormap to gray for viewing monochrome images image To display an image, e.g., image(A) displays the image contained in the matrix A imagesc Scales the image to use the full dynamic range and displays the scaled image imshow For displaying images movie To create and display a sequence of frames Images [x,map]=... imread('peppers.png'); image(x) colormap(map) Image I/O imread, imwrite, iminfo Image display image Display imagesc Scale and display a = magic(4); image(a); map = hsv(16); colormap(map) colorbar Image Processing Toolbox Image display imshow Display subimage Display multiple images in a single figure even if they have different colormaps Image exploration imtool Provides tools for pixel information, pixel region, distance, image information, adjust contrast, crop image, and display range Movie Player implay Play movie, video, or image sequence Multi-frame to movie immovie - Make MATLAB movie from a multiframe image Reading an Image: RGB_Image(row, column, rgb value)

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

Image1=imread(Lena.jpeg); figure imshow(Image1) %Prepare a 2D Image as a Matrix RGB_Matrix=zeros( 6. The matrix/vector data structures of Matlab enable many complicated mathematical equations to be expressed very concisely and computed very efficiently. A little thinking before beginning to program can be very beneficial! A simple example: given two 16 16-pixel blocks represented by matrices A and B, the sum of absolute difference (SAD) between them can be computed by either A method: SAD = 0; for i = 1:16, for j = 1:16, SAD = SAD + abs(A(i,j)-B(i,j)); end end or by B Method: SAD = sum(sum(abs(A - B))); Note that the second approach exploits Matlabs use of matrices and vectors, and does not require any for loops. im=imread('cameraman.tif'); figure,imshow(im); 10 s=size(im); temp=im; thresh=128; for i=1:s(1,1) for j=1:s(1,2) if temp(i,j)<thresh temp(i,j)=0; else temp(i,j)=255; end end end

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
figure, imshow(temp); Edge Detection Video Based Segmentation

2D Convolution for Images for Edge Detection

I1 ( x, y) I 2 ( x, y) = I1 ( x k , y m) I 2 ( k , m)
x = 0 y =0

N 1 M 1

Image1=zeros(Ncols, Mrows, double); Image2=zeros(Ncols, Mrows, double); 2D_Convolution=0; k=0:1:3; m=0:1:3; for y=1:Ncols, for x=1:Mrows, Image1(x,y)=I1(x-k,y-m); Image2(x,y)= I1(k, m); 2D_Convolution=2D_Convolution+ Image1(x,y).*Image2(x,y); 2D_Convolution=2D_Convolution+ I1(x-k,y-m).* I1(k, m); end end 2D_Convolution; Canny Edge Dedector Prewitt edge detector

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
Video Format: AVI: Audio Video Interleave MPEG: Mooving Picture Experts Group Raw: Raw Video MPEG-1 (.mpg), Windows Media Video (.wmv, .asf, .asx), MPEG-1 (.mpg), MPEG-4 (.mp4, .m4v), Apple QuickTime Movie (.mov), Video Media Player (from Simulink) mplay - View video from MATLAB workspace, multimedia file, or Simulink model AVI aviread, avifile, addframe, close, aviinfo Allows frame-byframe manipulation of AVI files movie2avi Make AVI file from MATLAB movie Video Multimedia reader mmreader, read, mmfileinfo - Allows frame-by-frame manipulation of video files Newer and better than counterpart AVI functions Supports many formats using installed Windows video codecs Video reader & writer videoReader, videoWriter - Read and write video data from a file videoReader replaces mmreader videoWriter replaces counterpart AVI functions VideoWriter supports only 'Motion JPEG AVI' and 'Uncompressed AVI Image Acquisition Toolbox Acquire images and video Support for a large range of imaging devices Video and Image Processing Blockset Multimedia I/O, video viewer, and display blocks Can work in real-time Can read from / write to MATLAB workspace read_video.m function [Y,U,V]=read_video(filename,height,width,length) %function [R,G,B]=read_video(filename,height,width,length) fid=fopen(filename,'r'); e=fread(fid); fclose(fid); t=1; for k=1:1:length for i=1:1:height

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
for j=1:1:width Y(i,j,k)=e(t); t=t+1; end end for i=1:1:(height/2) for j=1:1:(width/2) U(i,j,k)=e(t); t=t+1; end end for i=1:1:(height/2) for j=1:1:(width/2) V(i,j,k)=e(t); t=t+1; end end end RGB2YUV.m function [Y,U,V]=RGB2YUV(filename,length) T = [.299 .587 .114; -.169 -.332 .5;.5 -.419 -0.0813]; for i=1:1:length num=int2str(i-1); p='.ppm'; name=strcat(filename,num,p); A1 = imread(name); if ((rem(size(A1,1),2)~=0)) A=A1(1:(size(A1,1)-1),:,:); end if (rem(size(A1,2),2)~=0) A=A1(:,1:(size(A1,2)-1),:); end R(:,:,i)=double(A(:,:,1)); G(:,:,i)=double(A(:,:,2)); B(:,:,i)=double(A(:,:,3)); yuv = zeros(size(R,1),size(R,2),3); yuv(:,:,1) = T(1,1) * R(:,:,i) + T(1,2) * G(:,:,i) + T(1,3) * B(:,:,i) ; yuv(:,:,2) = T(2,1) * R(:,:,i) + T(2,2) * G(:,:,i) + T(2,3) * B(:,:,i) + 128; yuv(:,:,3) = T(3,1) * R(:,:,i) + T(3,2) * G(:,:,i) + T(3,3) * B(:,:,i) + 128; yuv = uint8(round(yuv)); Y(:,:,i)=yuv(:,:,1);

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
U(:,:,i)=imresize(yuv(:,:,2),1/2,'bicubic'); V(:,:,i)=imresize(yuv(:,:,3),1/2,'bicubic'); End YUV2RGB.m function [R,G,B]=YUV2RGB(Y,U,V) T=[.299 .587 .114; -.169 -.332 .5;.5 -.419 -0.0813]; P=inv(T); L=size(Y,3); for i=1:1:L yuv(:,:,1) = double(Y(:,:,i)); yuv(:,:,2) = imresize(double(U(:,:,i)),2,'bicubic'); yuv(:,:,3) = imresize(double(V(:,:,i)),2,'bicubic'); rgb = zeros(size(Y,1),size(Y,2),3); yuv(:,:,1) = yuv(:,:,1); yuv(:,:,2) = yuv(:,:,2) - 128; yuv(:,:,3) = yuv(:,:,3) - 128; rgb(:,:,1) = P(1,1) * yuv(:,:,1) + P(1,2) * yuv(:,:,2) + P(1,3) * yuv(:,:,3); rgb(:,:,2) = P(2,1) * yuv(:,:,1) + P(2,2) * yuv(:,:,2) + P(2,3) * yuv(:,:,3); rgb(:,:,3) = P(3,1) * yuv(:,:,1) + P(3,2) * yuv(:,:,2) + P(3,3) * yuv(:,:,3); R(:,:,i)=uint8(rgb(:,:,1)); G(:,:,i)=uint8(rgb(:,:,2)); B(:,:,i)=uint8(rgb(:,:,3)); end write_yuv1.m function write_yuv1(filename,Y,U,V) for k=1:1:(size(Y,3)) tt1=reshape((Y(:,:,k))',((size(Y,1))*(size(Y,2))),1); tt2=reshape((U(:,:,k))',((size(U,1))*(size(U,2))),1); tt3=reshape((V(:,:,k))',((size(V,1))*(size(V,2))),1); C(:,:,k) = horzcat(tt1',tt2',tt3'); end e=reshape(C,1,((size(C,1))*(size(C,2))*(size(C,3)))); ee=e'; fid = fopen(filename,'w'); fwrite(fid,ee,'uint8'); fclose(fid);

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
Section 1 Reading Uncompressed Video: If you have raw video, then handling in MATLAB is quite easy. Get familiar with the following functions: avifile, aviinfo, aviread, mmfileinfo mmreader movie2avi VideoReader VideoWriter frame2im, im2frame, addframe Web-link Reference http://www.mathworks.com/help/techdoc/ref/aviread.html Syntax mov = aviread(filename) mov = aviread(filename, index) Description mov = aviread(filename) reads the AVI movie filename into the MATLAB movie structure mov. If filename does not include an extension, then .avi is used. Use the movie function to view the movie mov. How To Read Any Video using Matlab After completing this now paste below code to your matlab screen.

aviinfo('Minoru 3D Webcam Video1.avi') Filename: [1x113 char] FileSize: 662420992 FileModDate: '01--2010 15:00:09' NumFrames: 728 FramesPerSecond: 15 Width: 640 Height: 480 ImageType: 'truecolor' VideoCompression: 'none' Quality: 0 NumColormapEntries: 0 AudioFormat: 'PCM' AudioRate: 44100 NumAudioChannels: 2

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

1st Method: How to Read a Video Streaming File aviread


Read Audio/Video Interleaved (AVI) file

http://www.mathworks.com/help/techdoc/ref/aviread.html

Syntax
mov = aviread(filename) mov = aviread(filename, index)

Description
mov = aviread(filename) reads the AVI movie filename into the MATLAB movie structure mov. If filename does not include an extension, then .avi is used. Use the movie function to view the movie mov.

AVI_Movie=aviread('Minoru 3D Webcam Video1.avi') Warning: AVIREAD will be removed in a future release. Use MMREADER instead. AVI_Movie = 1x728 struct array with fields: cdata colormap start=1; finish=1000; tic; %arvideo = aviread(filename,start:finish); toc mplay(AVI_Movie) Some Programming Tips using aviread mov = aviread('output.avi'); movie(mov); AVI_Movie=aviread('test.avi');

for j = 1:25 frame = ball(j); frameimage = frame.cdata; figure;

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

subplot(221);imshow(frameimage); A=im2bw(frameimage); subplot(222);imshow(A); end Another Method to Read the Video File clc; close all; clear all; %Following code converts given video (in.avi) to QVGA (320x240) resolution %video (out.avi). This example shows how to use video related functions in %MATLAB. For further details and other functions see MATLAB help. /***************************************/ % Example to scale a given video to QVGA (320x240) resolution %fin = 'e:\in.avi'; % Here in.avi is my video filename fin = ('Minoru 3D Webcam Video1.avi') %fout = 'd:\out.avi'; fout= 'NewVideo.avi'; fileinfo = aviinfo(fin); Filename: [1x113 char] FileSize: 662420992 FileModDate: [1x20 char] NumFrames: 728 FramesPerSecond: 15 Width: 640 Height: 480 ImageType: 'truecolor' VideoCompression: 'none' Quality: 0 NumColormapEntries: 0 AudioFormat: 'PCM' AudioRate: 44100 NumAudioChannels: 2 nframes = fileinfo.NumFrames; %Generate an AVI Video File with the FileName NewVideo AVI_VideoObject = avifile(fout, 'compression', 'none', 'fps', fileinfo.FramesPerSecond); for i = 1:nframes %Read frames from input video mov_in = aviread(fin,i); im_in = frame2im(mov_in);

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

%Do processing on each frame of the video %In this example - scaling [ht wd ch] = size(im_in); im_out = imresize(im_in, [240 320], 'bilinear'); %Write frames to output video frm = im2frame(im_out); aviobj = addframe(aviobj,frm); i %Just to display frame number end; %Don't forget to close output file aviobj = close(aviobj); return; /***************************************/ 2nd Method: How to Read a Video Streaming File mmreader
Use mmreader with the read method to read video data from a multimedia file into the MATLAB workspace. http://www.mathworks.com/help/techdoc/ref/mmreaderclass.html The file formats that mmreader supports vary by platform, as follows (with no restrictions on file extensions): All Platforms Motion JPEG 2000 (.mj2) Windows AVI (.avi), MPEG-1 (.mpg), Windows Media Video (.wmv, .asf, .asx), and any format supported by Microsoft DirectShow

Construction
obj = mmreader(filename) constructs obj to read video data from the file named filename. The mmreader constructor searches for the file on the MATLAB path. If it cannot construct the object for any reason, mmreader generates an error. obj = mmreader(filename,'PropertyName',PropertyValue) constructs the object using
options, specified as property name/value pairs. Property name/value pairs can be in any format that the set method supports: name/value string pairs, structures, or name/value cell array pairs.

Properties
BitsPerPixel Duration FrameRate Height Bits per pixel of the video data. (Read-only) Total length of the file in seconds. (Read-only) Frame rate of the video in frames per second. (Read-only) Height of the video frame in pixels. (Read-only)

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
Name NumberOfFrames Name of the file associated with the object. (Read-only) Total number of frames in the video stream. (Read-only) Some files store video at a variable frame rate, including many Windows Media Video files. For these files, mmreader cannot determine the number of frames until you read the last frame. When you construct the object, mmreader 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 = mmreader('varFrameRateFile.wmv'); lastFrame = read(vidObj, inf); numFrames = vidObj.NumberOfFrames; For more information, see Reading Variable Frame Rate Video in the MATLAB Data Import and Export documentation. Path String containing the full path to the file associated with the reader. (Read-only) User-defined string to identify the object. Default: '' Class name of the object: 'mmreader'. (Read-only) Generic field for user-defined data. Default: [] String indicating the MATLAB representation of the video format, such as 'RGB24'. (Read-only) Width of the video frame in pixels. (Read-only)

Tag

Type UserData

VideoFormat

Width

Fresh a New Start in your MATLAB workspace clc; clear all; close all; 2.1 MM_Movie=mmreader('Minoru 3D Webcam Video1.avi') Summary of Multimedia Reader Object for 'Minoru 3D Webcam Video1.avi'. Video Parameters: 15.00 frames per second, RGB24 640x480. 729 total video frames available.

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

If we try to test and play the video with the following matlab instructions no result will be obtained, mplay(MM_Movie) movie(MM_Movie) We need to write some programming code or script in order to prepare the Video Object file such as, MM_VideoObject=mmreader('Minoru 3D Webcam Video1.avi'); get(MM_VideoObject) General Settings: Duration = 48.6000 Name = Minoru 3D Webcam Video1.avi Path = C:\Program Files\MATLAB\R2010b\work\Video Object Detection and Segmentation Algorithm Tag = Type = VideoReader UserData = [] Video Settings: BitsPerPixel = 24 FrameRate = 15.0000 Height = 480 NumberOfFrames = 729 VideoFormat = RGB24 Width = 640 We can get the above video information instead of using the get instruction by using the following Matlab instructions: info = mmfileinfo('Minoru 3D Webcam Video1.avi ') audio = info.Audio video = info.Video Write the following code: nFrames = MM_VideoObject.NumberOfFrames; vidHeight = MM_VideoObject.Height; vidWidth = MM_VideoObject.Width; % Preallocate and Generate a movie structure. mov(1:nFrames) = ...

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

struct('cdata', zeros(vidHeight, vidWidth, 3, 'uint8'),... 'colormap', []); % Read one frame at a time. for k = 1 : nFrames mov(k).cdata = read(MM_VideoObject, k); end % Size a figure based on the video's width and height. hf = figure; set(hf, 'position', [150 150 vidWidth vidHeight]) % Play back the movie once at the video's frame rate. movie(hf, mov, 1, MM_VideoObject .FrameRate); Another Method to Read the Video File Clc; Close all; Clear all; start=1; finish=300; tic; MM_VideoObject= mmreader(filename); MM_Video= read(MM_VideoObject,[start finish]); toc Some Programming Tips using mmreader MM_VideoObject=mmreader('Minoru 3D Webcam Video1.avi'); MM_Video=read(MM_VideoObject); frames=get(MM_Video,'numberOfFrames'); for k = 1 : frames-1 I(k).cdata = a(:,:,:,k); I(k).colormap = []; end %Reading a video and converting it to frame then into image fileinf = mmreader('Minoru 3D Webcam Video1.avi'); nframes = get(fileinf, 'numberOfFrames'); mov_in = read(fileinf,1); [im , map] = frame2im(mov_in); ??? Error using ==> frame2im

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

for i = 1:nframes % display your image here M(i) = getframe(gcf); end mplay(M) 3rd Method: How to Read a Video Streaming File ReadVideo
The Read Video reads the Video Frames and Converts them into Images of Double data

function [ vidHeight,vidWidth,nFrames,vid ] = ReadVideo( FileName , frameSkip,startFrame,endFrame ) %Video Input video=mmreader(FileName); %read a video in this range if endFrame == 0 && endFrame<=startFrame nFrames = floor((video.NumberOfFramesstartFrame)/frameSkip); else nFrames =floor((endFrame - startFrame)/frameSkip); end vidHeight = video.Height; vidWidth = video.Width; fprintf('Start read video : nFrames=%d H:%d W:%d\n',nFrames,vidHeight,vidWidth); fprintf('frameSkip:%d startFrame:%d endFrame:%d\n',frameSkip,startFrame,endFrame); %create array for vid vid=ones(vidHeight,vidWidth,nFrames); for i=1:nFrames % read frame p = read(video, i*frameSkip + startFrame); % convert to grayscale and double vid(:,:,i)= im2double(rgb2gray(p)); end % free the memory for video
Prepared by Lakis Christodoulou 425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

clear p

if(max(max(vid(:,:,1)))>1) vid=vid/255; end end [ vidHeight,vidWidth,nFrames,vid ] = ReadVideo( 'Minoru 3D Webcam Video1.avi',3,1,0 ); [ vidHeight,vidWidth,nFrames,vid ]; mplay(vid) % Reading and understanding what is a Video Stream as an Array-Matrix % 480 640 215 double % Let j be my n_rows index with m=vidWidth=640 n_rows= vidHeight; % Let i be my n_cols index with m=vidHeight=480 n_cols= vidWidth; % Let k be my n_frames index with n_frames=nFrames=215 n_frames=nFrames; % Reallocate Memory and Create a new Video Stream-Channel with same % Array-Matrix Dimensions Video_Stream=zeros(n_rows,n_cols,n_frames); for k=1:n_frames-1 for i=1:n_cols-1 for j=1:n_rows-1 Video_Stream(j,i,k)= vid(j,i,k);

end end end Video_Stream_1= Video_Stream; Video_Stream_2= Video_Stream; mplay(Video_Stream_1)

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

%Video_Stream_1=uint8(Video_Stream); %mplay(Video_Stream_1) Apply a Filter on the Video_Stream Write a small Program such as the following Matlab Sub-rutine % Reallocate Memory and Create new Video Stream-Channels with same % Array-Matrix Dimensions Video_Stream_Denoising_1=zeros(n_rows,n_cols,n_frames,n_pixels); Video_Stream_Denoising_2=zeros(n_rows,n_cols,n_frames); Video_Stream_Denoising_3=zeros(n_rows,n_cols,n_frames); Use fspecial Matlab instruction FSPECIAL Create predefined 2-D filters. H = FSPECIAL(TYPE) creates a two-dimensional filter H of the specified type. Possible values for TYPE are: 'average' averaging filter 'disk' circular averaging filter 'gaussian' Gaussian lowpass filter 'laplacian' filter approximating the 2-D Laplacian operator 'log' Laplacian of Gaussian filter 'motion' motion filter 'prewitt' Prewitt horizontal edge-emphasizing filter 'sobel' Sobel horizontal edge-emphasizing filter 'unsharp' unsharp contrast enhancement filter gaussian filter Gaussian_F= fspecial('gaussian'); Average_F= fspecial('gaussian',1,20); Laplacian_F= fspecial('gaussian',1,20); for k=1:n_frames-1 for i=1:n_cols-1 for j=1:n_rows-1 Video_Stream_Denoising_1(j,i,k)=imfilter(vid(j,i,k),Gaussian_F);

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

end end end

Video_Stream_Denoising_1(j,i,k); mplay(Video_Stream_Denoising_1) for figure(1), subplot(1) imshow(Video_Stream); subplot(2) imshow(Video_Stream_Denoising_1); end 4th Method: How to Read a Video Streaming File ReadVideo
http://www.mathworks.com/help/techdoc/ref/videoreaderclass.html

In your Matlab WorkSpace create a New M-Script file clc; closel clear all; Construct a VideoReader object for the demo movie file xylophone.mpg and view its properties: VideoObject = VideoReader('Minoru 3D Webcam Video1.avi'); get(VideoObject)

Read and play back the movie file xylophone.mpg: xyloObj = VideoReader('xylophone.mpg'); nFrames = VideoObject.NumberOfFrames; vidHeight = VideoObject .Height; vidWidth = VideoObject.Width;
Prepared by Lakis Christodoulou 425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

% Preallocate movie structure. mov(1:nFrames) = ... struct('cdata', zeros(vidHeight, vidWidth, 3, 'uint8'),... 'colormap', []); % Read one frame at a time. for k = 1 : nFrames mov(k).cdata = read(VideoObject, k); end % Size a figure based on the video's width and height. hf = figure; set(hf, 'position', [150 150 vidWidth vidHeight]) % Play back the movie once at the video's frame rate. movie(hf, mov, 1, VideoObject .FrameRate); 4th Method: How to Read a Video Streaming File WriteVideo
http://www.mathworks.com/help/techdoc/ref/videowriterclass.html
Write video files

Description
Use the VideoWriter function with the open, writeVideo, and close methods to create video files from figures, still images, or MATLAB movies. Supported file formats include AVI and Motion JPEG 2000. VideoWriter can write files larger than 2 GB, which is the limit for avifile. To set video properties, VideoWriter includes predefined profiles such as 'Motion JPEG AVI' or 'Uncompressed AVI'.

Construction
writerObj = VideoWriter(filename) constructs a VideoWriter object to write video data to
a file.

writerObj = VideoWriter(filename,profile) applies a set of properties tailored to a specific file format (such as 'Uncompressed AVI') to an VideoWriter object.
Input Arguments
filename
String enclosed in single quotation marks that specifies the name of the file to create.

VideoWriter supports the extension .avi for AVI files, or .mj2 for Motion JPEG 2000 files. If you specify a Motion JPEG 2000 profile, and do not specify an extension, VideoWriter appends the extension .mj2. If you do not specify a profile, VideoWriter creates an AVI file with the extension .avi, and uses Motion

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
JPEG compression.

profile

String enclosed in single quotation marks that describes the type of file to create. Specifying a profile sets default values for video properties such as VideoCompressionMethod. Possible values: Compressed AVI file using Motion JPEG codec (default)

'Motion JPEG AVI'

'Uncompressed AVI' 'Motion JPEG 2000' 'Archival'

Uncompressed AVI file with RGB24 video Compressed Motion JPEG 2000 file Motion JPEG 2000 file with lossless compression

VideoWriter supports all profiles on all platforms.

Properties
ColorChannels
Number of color channels in each output video frame. (Read-only) AVI files have three color channels (RGB). The number of channels for Motion JPEG 2000 files depends on the input data to the writeVideo method: one for monochrome image data, three for color data.

CompressionRatio

Number greater than 1 that specifies the target ratio between the number of bytes in the input image and the number of bytes in the compressed image. The data is compressed as much as possible, up to the specified target. Only available for objects associated with Motion JPEG 2000 files. After you call open, you cannot change the CompressionRatio value. If you previously set LosslessCompression to true , setting CompressionRatio generates an error. Default: 10

Duration FileFormat Filename FrameCount FrameRate

Scalar value specifying the duration of the file in seconds. (Read-only) String specifying the type of file to write: 'avi' or 'mj2'. (Read-only) String specifying the name of the file. (Read-only) Number of frames written to the video file. (Read-only) Rate of playback for the video in frames per second. After you call open, you cannot change the FrameRate value. Default: 30

Height

Height of each video frame in pixels. The writeVideo method sets values for Height and Width based on the dimensions of the first frame. (Read-only) Boolean value (logical true or false) only available for objects associated with Motion JPEG 2000 files. If true: The writeVideo method uses reversible mode so that the decompressed data is identical to the input data.

LosslessCompression

VideoWriter ignores any specified value for CompressionRatio.


After you call open, you cannot change the LosslessCompression value. Default: false for the 'Motion JPEG 2000' profile, true for the 'Archival'

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis
profile

MJ2BitDepth

Number of least significant bits in the input image data, from 1 to 16. Only available for objects associated with Motion JPEG 2000 files. If you do not specify a value before calling the open method, VideoWriter sets the bit depth based on the input data type. For example, if the input data to writeVideo is an array of uint8 or int8 values, MJ2BitDepth is 8.

Path Quality

String specifying the fully qualified path. (Read-only) Number from 0 through 100. Higher quality numbers result in higher video quality and larger file sizes. Lower quality numbers result in lower video quality and smaller file sizes. Only available for objects associated with the Motion JPEG AVI profile. After you call open, you cannot change the Quality value. Default: 75

VideoBitsPerPixel

Number of bits per pixel in each output video frame. (Read-only) AVI files have 24 bits per pixel (8 bits for each of three color bands). For Motion JPEG 2000 files, the number of bits per pixel depends on the value of MJ2BitDepth and the number of bands of image data. For example, if the input data to writeVideo is a three-dimensional array of uint16 or int16 values, the default value of MJ2BitDepth is 16, and VideoBitsPerPixel is 48 (three times the bit depth).

VideoCompressionMethod String indicating the type of video compression: 'None', 'Motion JPEG', or 'Motion JPEG 2000'. (Read-only) VideoFormat
String indicating the MATLAB representation of the video format. (Read-only) For AVI files, VideoFormat is 'RGB24'.

Example
Construct a VideoWriter object and view its properties. Set the frame rate to 60 frames per second: myObj = VideoWriter('newfile.avi'); % Type object names to see properties. myObj % Set and view the frame rate. myObj.FrameRate = 60 Write a sequence of frames to a compressed AVI file, peaks.avi: % Prepare the new file. vidObj = VideoWriter('peaks.avi'); open(vidObj);

Prepared by Lakis Christodoulou

425

425 - Matlab 425 DIP Image Video Processing using Matlab 425 DIP Matlab Programming FALL 2011 Basic Image Video Processing and Analysis

% Create an animation. Z = peaks; surf(Z); axis tight set(gca,'nextplot','replacechildren'); for k = 1:20 surf(sin(2*pi*k/20)*Z,Z) % Write each frame to the file. currFrame = getframe; writeVideo(vidObj,currFrame); end % Close the file. close(vidObj);
/***************************************/ %Script file to combine images to an uncompressed avi file %Directory that contains images in_dir = 'Q:\temp\ffmpeg.rev11870\images\'; fout = 'q:\out1.avi'; %Output file name num_images = 341; %Number of images %Set a suitable frame rate fps aviobj = avifile(fout, 'compression', 'none', 'fps', 25); for i = 1:num_images; temp = sprintf('%d', i); name = [in_dir, 'image_', temp, '.bmp']; %For ppm, change img = imread(name); frm = im2frame(img); aviobj = addframe(aviobj,frm); i end; aviobj = close(aviobj); return;

Prepared by Lakis Christodoulou

425

You might also like