video to frames in matlab - matlab

I have a code to extract frames from a video.The code is given below
addpath('E:\project\coding\wrk_ongoing\Images');
obj = mmreader('ace.mp4');
vid = read(obj);
frames = obj.NumberOfFrames; %Read the Total number of frames and displyed in command window
ST='.jpg';
cd frames
for x = 1:5 % extracting the 5 frames from video
Sx=num2str(x);
Strc=strcat(Sx,ST);
Vid=vid(:,:,:,x);
imwrite(Vid,Strc);
end
cd ..
This code works only for some videos.I tested for different videos with .mp4 extension.Some of them works well. But input videos shows error as
??? Error using ==> vid2frame at 6
Initialization failed. (No combination of intermediate filters could be found to make the
connection.)
how can I solve this ?

That error is due to your video file itself. From the looks of it, MATLAB has a problem reading that file probably because the file is badly encoded or the video was encoded with a codec that is not supported by MATLAB or does not exist on your computer.. See this question for a similar problem: no combination of intermediate filters could be found
This has nothing to do with MATLAB, but the error was what you encountered and the answer was to essentially re-encode the video file in a format that is compatible with your operating system and MATLAB.
Good luck!

Related

MATLAB: Use of vision.VideoFileWriter and vision.VideoFileReader

I'm trying to convert a .avi file with audio to a .mp4 file. I wrote this script 'avi2mp4.m' using the Computer Vision System Toolbox v7.2 with the MATLAB R2016b.
vfr = vision.VideoFileReader('Cris Drift vs Patrick.avi', 'AudioOutputPort',true);
vfw = vision.VideoFileWriter('Cris Drift vs Patrick.mp4', 'FileFormat','MPEG4', 'AudioInputPort',true, ...
'FrameRate',vfr.info.VideoFrameRate, 'Quality',90);
while ~isDone(vfr)
[frame, audio] = vfr(); % [frame, audio] = step(vfr);
vfw(frame, audio); % step(vfw, frame, audio);
end
release(vfr);
release(vfw);
but i get this error:
Error using vision.VideoFileWriter/parenReference
Too many input arguments; expected 1 (in addition to the object handle), got 2.
Error in avi2mp4 (line 16)
vfw(frame, audio);
I don't know why? I have to pass the audio data as an argument to write it with the video data. It's the same syntax as described in the MATLAB Documentation
Documentation for Video File Writer Object
Documentation for Video File Reader Object
With vision.VideoFileWriter you can write both audio and video only when the format is AVI or WMV. If you received a warning about AudioInputPort property not relevant when you set that property that means audio is not supported in that configuration.

How to create a grayscale video

I wrote a code in Matlab, in which I have to read a color video, retrieve the frames from the video perform some operations with the frames and then again make a video from the operated frames i wrote a simple code for converting each frame to gray-scale and thus generating the gray-scale video and it showed the following error:
Warning: No video frames were written to this file. The file may b invalid.
In VideoWriter.VideoWriter>VideoWriter.close at 307
In VideoWriter.VideoWriter>VideoWriter.delete at 256
In getFrames2Image at 9
Following is the code i wrote
a=VideoReader('test.mp4');
images=cell(a.NumberOfFrames,1);
for img=1:a.NumberOfFrames
b=read(a,img);
c=rgb2gray(b);
images{img}=b;
end
outp=VideoWriter('output');
outp.FrameRate=30;
open(outp);
for i=1:length(images)
frame=im2frame(images{i});
writeVideo(outp,frame);
end
close(outp);
As requested here are the details of my matlab version:
Matlab R2013a(8.1.0.604)
64 bit(win64)
and link of the sample video
https://drive.google.com/open?id=0B-MZ8myQc4ZKU0E1dURPRUhwd1k

Unable to create audio compressor filter

Function takes as input a string, the name of the video. It's read the video with the vision.VideoFileReader function and returns the same video, using thevision.VideoFileWriter function. Both the input video that the output videos have audio. Processing of a video about 6 MB, i have the output of a video more than 1 GB. The function has no errors, but i have to compress. Using the VideoCompressor, can compress the video up to 350 MB, i would use theAudioCompressor, but by obtaining an error.
This is my code, the following is the error returned.
function [ nFrames ] = showMovie( video )
v = VideoReader(video);
videoFReader = vision.VideoFileReader(video);
videoFWriter = vision.VideoFileWriter('FrameRate',v.FrameRate,'AudioInputPort',1,'VideoCompressor', 'MJPEG Compressor','AudioCompressor','MJPEG Compressor');
[audio,fs] = audioread(video);
op=floor(fs/v.FrameRate);
nFrames = 0;
while ~isDone(videoFReader)
nFrames=nFrames+1;
frame=step(videoFReader);
audios=audio( (nFrames-1)*op + 1 : nFrames*op , : );
step(videoFWriter,frame,audios);
end
release(videoFReader);
release(videoFWriter);
end
I can't use the property AudioCompressor. I tried both the Compressor MJPEG and the DV Video Encoder value, but I get this error:
Error using VideoFileWriter / step
Unable to create audio compressor filter
Error in showMovie (line 15)
step (videoFWriter, frame, audios);
You're trying to specify a video compressor for your audio which is resulting in the error. Different compression algorithms are used for the audio and video components. You need to specify a valid audio compressor.
To get a list of available options on your machine, you can use tab completion in the command window:
videoWriter.AudioCompressor = ' % <tab> key
As Rotem has noted, this list can also include Video compression algorithms, but it should also include any valid audio compression algorithms for which you have the correct codecs installed.
The only AudioCompressor compressor that works in my system is: 'None (uncompressed)'
I tried it on 64 bit version of Matlab (R2014b).
The reason for that is that my Windows system lacks x64 (64 bit) audio codec supported by Matlab.
Note: 64 bit Matlab requires x64 codecs, and 32 bit Matlab requires x86 codecs.
When I use videoWriter.AudioCompressor = ' % <tab> key as Suever mentioned,
When I tried the same code using 32 bit version of Matlab (R2013b), I got the following list:
AC-3 ACM Codec
AC-3 ACM Extensible
CCITT A-Law
CCITT U-Law
GSM 6.10
IMA ADPCM
Microsoft ADPCM
None (uncompressed)
Note: The video codecs shown in 64 bit version, are not displayed in the 32 bit Matlab.
I guess displaying video codecs in AudioCompressor is a Matlab bug.
Just for the record, I tried the <tab> key before Suever posed his answer.
I read about it in Matlab documentation: http://www.mathworks.com/help/vision/ref/vision.videofilewriter-class.html
To launch the tab completion functionality, type the following up to the open quote.
y.VideoCompressor='
A list of compressors available on your system will appear after you press the Tab key
The following code sample works in system:
video = 'xylophone.mpg';
v = VideoReader(video);
videoFReader = vision.VideoFileReader(video);
videoFWriter = vision.VideoFileWriter('FrameRate',v.FrameRate,'AudioInputPort',1,'VideoCompressor', 'MJPEG Compressor','AudioCompressor', 'None (uncompressed)');
[audio,fs] = audioread(video);
op=floor(fs/v.FrameRate);
nFrames = 0;
while ~isDone(videoFReader)
nFrames=nFrames+1;
frame=step(videoFReader);
audios=audio( (nFrames-1)*op + 1 : min(nFrames*op, length(audio)) , : );
%Handle last audio sample.
if (length(audios) < op)
audios = [audios; audios(1:op - length(audios), :)];
end
step(videoFWriter,frame,audios);
end
release(videoFReader);
release(videoFWriter);
I was searching the Web for free x64 audio codec that works with Matlab, but I couldn't find one.

MATLAB loading and saving a single image from a 32 bit tiff stack

I'm using MATLAB_R2011a_student. I have some image stacks saved as 32 bit tiffs, some over 1000 frames. I would like to be able to pull out a specific frame from the stack and save it as a 32 bit tiff or some readable format where there would be no data loss from the original. Currently my code looks like this:
clear, clc;
k=163;
image=('/Users/me/Filename.tiff');
A = uint8(imread(image, k));
B=A(:,:,1);
J=imadjust(B,stretchlim(B),[]);
imwrite(J,'/Users/me/163.tif','tif');
(I'm assuming reading it as 8 bit, and the way I'm saving are not the best way to do this)
Either way this code works for a seemingly random number of frames (for example in one file.tiff the above code works for frames 1-165 but none of the frames after 165, for a different file.tiff the code works for frames 1-8 but none of the frames after 8) I'm also getting a strange horizontal line in the output image when this does work:
??? Error using ==> rtifc
Invalid TIFF image index specified.
Error in ==> readtif at 52
[X, map, details] = rtifc(args);
Error in ==> imread at 443
[X, map] = feval(fmt_s.read, filename, extraArgs{:});
Thanks!
The best way (in my opinion) to handle tiff stacks is to use the Tiff library available since a few years. I must admit that I don't know much about OOP but I managed to understand enough to load a tiff stack and manipulate it.That's the kind of simple demo I wish I had seen a year ago haha.
I the following example I load a single stack and store it all into a 3D array. I use imfinfo to fetch infos about the images, notably the number of images/stack and the actual image dimensions. If you want you can choose to load only one image using appropriate indices. Please try the code below and play around with it; you'll understand what I mean.
clear
clc
%// Get tiff files you wish to open
hFiles = dir('*.tif');
%// Here I only have 1 multi-tiff file containing 30 images. Hence hInfo is a 30x1 structure.
hInfo = imfinfo(hFiles(1).name);
%// Set parameters.
ImageHeight = hInfo(1).Height;
ImageWidth = hInfo(1).Width;
SliceNumber = numel(hInfo);
%// Open Tiff object
Stack_TiffObject = Tiff(hFiles.name,'r');
%// Initialize array containing your images.
ImageMatrix = zeros(ImageHeight,ImageWidth,SliceNumber,'uint32');
for k = 1:SliceNumber
%// Loop through each image
Stack_TiffObject.setDirectory(k)
%// Put it in the array
ImageMatrix(:,:,k) = Stack_TiffObject.read();
end
%// Close the Tiff object
Stack_TiffObject.close
Hope that helps.

Failed to write stream data, matlab

I have writtring a script that convert a set of BMPs to avi. up until recently it worked fine. now I get this wierd error "Failed to write stream data". I get it after converting 5 libraries of bmps to avi. It runs over librarirs of BMPs and convert each library to avi. each time it stacks in the 6th movie.. there are no corrupts files in the 6th library. any idea why?
this is the code:
%this works
clc
%path='C:/Documents and Settings/Ariel/Desktop/exp_brk_scrm/2.1/group1/exp_up/exp_up/4python/stims';
%FullPath=strcat(path,'/mov1.avi');
path4avi='G:/experiments/cfs3/building/Copy of StimBMP/avi/'; %dont forget the in the end of the path
pathOfFrames='G:/experiments/cfs3/building/Copy of StimBMP/stims/'; %here too
NumberOfFiles=70; %to be generated
NumberOfFrames=8; %in each avi file
for i=1:1:(NumberOfFiles)
FileName=strcat(path4avi,'Stim',int2str(i),'.avi') %the generated files
aviobj = avifile(FileName,'compression','None'); %due to changes in the new Media Players
aviobj.fps=10;%10 frames in Sec
for j=1:1:(NumberOfFrames)
Frame=strcat(pathOfFrames,'stim',int2str(i),'/stim',int2str(j),'.BMP') % the BMP's (not a good name for thedirectory)
%[Fa,map]=imread(Frame);
%imshow(Fa,map); %
[Fa,map]=imread(Frame);
imshow(Fa,map);
% imshow(Fa);
F=getframe();
aviobj=addframe(aviobj,F)
end
aviobj=close(aviobj);
end
Hi I know this might seem a bit over simplified but I had the same issue.
My code worked fine and just one day stopped exactly as you have described. I found that it was just the destination I was writing my files to simply did not have enough memory for the video files. Deleted some junk I didn't need and it worked instantly. Matlab just doesn't realise the issue is with storage space so in my case it said there was an issue with its own 'movie2avi' function
Since I'm not sure what the source of your problem is, I'm just providing a simple working example of how to create an AVI movie. Demo images from the Image Processing Toolbox are used:
figure('Color','white')
aviObj = avifile('out.avi', 'fps',5); %# create AVI object
for i=1:10
I = imread( sprintf('AT3_1m4_%02d.tif',i) ); %# read image frame
imshow(I, 'Border','tight'), colormap gray %# show image
aviObj = addframe(aviObj, getframe(gcf)); %# grab frame and add to AVI
end
close(gcf)
aviObj = close(aviObj); %# close and write movie
winopen('out.avi') %# play movie in Windows
Does the order of the libraries matter? In other words, if you run the 6th first and the 1st last, will it crash on the first or on the last?
If it crashes on the first, then you library #6 has a problem
If it crashes on the last, you may be filling up memory somehwere. Use clear classes before running your script, which should eliminate whatever Matlab is filling up in the memory. Alternatively, if the leak or fragmentation is really bad, you could try and restart Matlab after three libraries.