Matlab Code to Convert Video to Sequence of Frames - matlab

hi can someone tell me whats wrong with my Matlab Code to Convert Video to Sequence of Frames . it doesn't work.
clc
clear all
close all
file=aviinfo('test.avi');
frm_cnt=file.NumFrames
FileExtension='.bmp'
h = waitbar(0,'Please wait');
for i=1:frm_cnt
% Read the Frame of the Video file
frm(i)=VIDEOREADER ('test1.avi',i);
% Convert Frame to image file
frm_name=frame2im(frm(i));
%Create Filename to store
Filename=strcat(strcat(num2str(i)),FileExtension);
% Write image file to the current folder
imwrite(frm_name,Filename);
waitbar(i/frm_cnt,h)
end
%Close Progress bar
close(h)

Try this :
shuttleVideo = VideoReader('shuttle.avi');
ii = 1;
while hasFrame(shuttleVideo)
img = readFrame(shuttleVideo);
filename = [sprintf('%03d',ii) '.jpg'];
fullname = fullfile(workingDir,'images',filename);
imwrite(img,fullname) % Write out to a JPEG file (img1.jpg, img2.jpg, etc.)
ii = ii+1;
end

Related

Loop for frame extraction matlab

Im currently trying to make a loop to do the same action to multiply videofiles. Currently my code looks like this:
close all
clear all
clc
movFiles = dir('*.mov');
numFiles = length(movFiles);
mydata = cell(1,numFiles);
% mydata = zeros(numFiles);
for k = 1:numFiles
mydata{1,k} = VideoReader(movFiles(k).name);
end
for k=1:numFiles
figure;
video = read(mydata{k},[1 Inf]);
for img = 60:60:360;
filename=strcat('File',num2str(img),'.jpg');
b = read(mydata{k}, img);
imwrite(b,filename);
end
end
The problem is that the frames get overwritten so what i need is a way to not make that happened. The moviefiles are named 1-200 so the filename i would like is something like 1framenr, 2framenr. Hope that somebody can help me with that
The problem is in the way you are defining the filename for each frame inside the loop. If you look at the line:
filename=strcat('File',num2str(img),'.jpg');
It is only composed of the frame number (img), which will repeat for every video file. Try replacing that line with following:
filename = ['Video_' num2str(k) '_frame_' num2str(img) '.jpg'];
This will give you files called Video_1_frame_1.jpg, Video_1_frame_2.jpg, etc.

Creating a stacked tiff file causes image offset

I have a an image processing program whose results need to be saved to a stacked tiff file. The code for the method that does this is included below. When the resulting image is opened in ImageJ it gives the notification "Unexpected image offset" and only can display the first image in the stack.
fig = figure;
figure(fig);
fileN = handles.fileName;
[m n] = size(fileN);
m = 0;
for i=1:n
if(fileN(i) == '.')
m = i;
break
end
end
fileN = fileN(:,1:m-1);
fileP = handles.filePath;
saveFilePath = strcat(fileP,fileN,'-snake-analysis.tif')
im = imread(handles.fileFull, 1);
imshow(im, []);
hold on
plot(handles.xsFinal(1,:), handles.ysFinal(1,:), 'r-');
hold off
saveas(fig, saveFilePath);
for i=2:handles.numFrames
im = imread(handles.fileFull, i);
imshow(im, []);
hold on
plot(handles.xsFinal(i,:), handles.ysFinal(i,:), 'r-');
hold off
saveas(fig, 'inter.tif');
a = imread('inter.tif');
imwrite(a, saveFilePath,'Compression', 'none','WriteMode','append');
delete 'inter.tif';
end
Does anyone know what is causing this problem?
The built-in ImageJ 1.x TIFF opener does not fully handle the baseline TIFF specification: it cannot handle out-of-sequence planes.
If you use ImageJ2, you can use the SCIFIO library to open your TIFF via the File ▶ Import ▶ Image... command. The Bio-Formats Importer plugin can also open such TIFF files.

Looping VideoReader in Matlab for processing

I've looked everywhere and I still cannot seem to successfully loop MATLAB's videoreader. I am trying to use MATLAB to process videos and convert them to saved image sequences which I can analyze by binary pixel properties for areas and such. I'm really new to MATLAB so any help would most certainly help.
Here is my code thus far for the image sequence creation. Also this is in R2015a.
function VideoToImageSequence(dirname,doall)
% load up the set of global variables
global settings
inpath = [settings.inpath, '\' , settings.dirname, '\'];
outpath = inpath;
%list of files
list = dir([inpath, '\*.avi']);
N =length(list);
display(['Found ', mat2str(N), ' movies in ', inpath]);
%Main converter
for i= 1:N
rootname{i} = list(i).name(1:end-4);
savefile = [rootname{i}, '.mat'];
if exist([inpath, savefile], 'file') && doall==0
display(['Found analyzed file ', savefile, ' .... skipping']);
else
%Directory
addpath(genpath([settings.inpath,'\', settings.dirname,'\' ,rootname{i}]));
workingDir = [settings.inpath,'\' , settings.dirname, '\' , rootname(i)];
cd([settings.inpath, '\', settings.dirname, '\'])
filename= rootname(i) ;
VideoFile = VideoReader(filename) ;
ii = 1;
%Spits out image sequence
while hasFrame(VideoFile(i))
img = readFrame(VideoFile(i));
filename = [sprintf('%03d',ii) '.jpg'];
fullname = fullfile(workingDir,'images',filename);
imwrite(img,fullname) % Write out to a JPEG file (img1.jpg, img2.jpg, etc.)
ii = ii+1;
end
end
end
Any help you can give would be awesome! Thanks.

frame to video conversion matlab

So I just started with image processing/computer vision in MATLAB.
So my first task is to convert a series of images(frames) into a video. So I went through online sources (MATLAB website more specifically) to get a way to do it.
So the one that I implemented is http://www.mathworks.com/help/matlab/examples/convert-between-image-sequences-and-video.html which solved the problem for me.
However, when I play it, the video seems jumpy in some places. Like it would bring a different frame in the middle and make the whole video jumpy for that split second. It happens a couple of places in the video.
Any anyone knows why this happens?
Thanks
PS below is the code I use:
myFolder = 'C:\Users\owner\Desktop\MATLAB GUI\Color\Color'; %Specify Directory
filePattern = fullfile(myFolder, '*.jpg') %identify jpg files
jpegFiles = dir(filePattern) %use dir to list jpg files
size = length(jpegFiles); % length of the size of the file
outputVideo = VideoWriter(fullfile(myFolder,'video1.avi'));
outputVideo.FrameRate = 30;
open(outputVideo);
for i = 1:length(jpegFiles) %load all the files in the directory
j = i; %%accumulating the number of jpegfiles into handles.j
baseFileName = jpegFiles(i).name;
fullFileName = fullfile(myFolder, baseFileName);
%fprintf(1, 'Now reading %s\n', fullFileName); %filename of image
imageArray = imread(fullFileName); %image being read
%imageArray = rgb2gray(imageArray);
imagecell{i} = imageArray; %storing the images in imagecells
writeVideo(outputVideo,imagecell{i});
end
close(outputVideo);
video1 = VideoReader(fullfile(myFolder,'video1.avi'));
mov(video1.NumberOfFrames) = struct('cdata',[],'colormap',[]);
for ii = 1:video1.NumberOfFrames
mov(ii) = im2frame(read(video1,ii));
end
set(gcf,'position', [150 150 video1.Width video1.Height])
set(gca,'units','pixels');
set(gca,'position',[0 0 video1.Width video1.Height])
image(mov(1).cdata,'Parent',gca);
axis off;
movie(mov,1,video1.FrameRate);
Given that there may be too many files to be renamed (padded with zeros) here is a quick function that will do it for you: you just need to provide the directory/folder where the images are stored, the padding (if less 100 files, then padding can be 2; if less than 1000 files, then padding can be 3; etc.), and a common pattern. The code assumes that there is a common pattern in each file (like 'frame' or 'image') that when removed, leaves just the number:
renameFiles(directory,padSize,fileNamePattern)
filePattern = fullfile(directory, '*.jpg') %identify jpg files
jpegFiles = dir(filePattern) %use dir to list jpg files
for k=1:size(jpegFiles)
% get the source file that will be moved/renamed
fileSrc = jpegFiles(k).name;
% get the parts of the file
[path,name,ext] = fileparts(fileSrc);
% where does the pattern fit in the name?
idx = strfind(name,fileNamePattern);
% remove the pattern from the name
if idx==0
% pattern does not exist in file so skip it
continue;
elseif idx==1
% pattern is at the beginning of name so remove it
frameNumberStr = name(length(fileNamePattern)+1:end);
else
% pattern is at the end of name so remove it
frameNumberStr = name(1:idx-1);
end
% get the number of digits
numDigits = length(frameNumberStr);
% create the new file name
paddedName = [fileNamePattern repmat('0',1,padSize-numDigits) frameNumberStr];
fprintf('%s\n',paddedName);
% only move if the destination is different
if strcmp(paddedName,name) ~= 1
% set the destination file
fileDest = fullfile(directory,[paddedName ext]);
% move the file
movefile(fileSrc, fileDest,'f');
end
end
end
An example - if all files have the common pattern of 'frame' and there are less than 1000 files, then run this function as
rename(pwd,3,'frame')
All files that were named as frame1.jpg or frame99.jpg are now named as frame001.jpg and frame099.jpg.
Hope this helps!
If you have the Computer Vision System Toolbox you can use the vision.VideoFileWriter object. You can simply feed images into its step() method one at a time, and they will be written to the video file as video frames. Note that the images must all be the same size and have the same data type.

Comparing several webcam snapshots and saving Them when there is motion Using matlab

My question is how would i get live snapshots from my webcam and only save an image when there is motion, I would like to save several images i.e whenever there is motion the images do not overwrite so that at the end i will be able to see various captured motions
well i was able to come up with a simple solution for my problem as below; it saves images only when there is motion and also adds a time stamp
clear;
clc;
vid = videoinput('winvideo', '1');
set(vid, 'ReturnedColorSpace', 'RGB');
start(vid)
%preview(vid)
while true;
img = getsnapshot(vid);
pause(2)
img1 = getsnapshot(vid);
img12 = rgb2gray(img1);
img13 = rgb2gray(img);
diff1 =sum(sum(img12 - img13));
if diff1>100000;
display ('motion')
counter = 1;
baseDir = 'H:\';
fname = [baseDir ,'Wysla_', num2str((strrep(datestr(clock),':','-'))),'.jpg'];
% make a file name
while exist(fname,'file')
counter = counter + 1;
fname = [baseDir ,'Wysla_', num2str(counter),'.jpg'];
end
imwrite(img1, fname);
else
display('No motion')
end;
end
This is all and it was very simple only thing i can mention is the strrep(datestr(clock),':','-') this a way of saving the image time stamped and since there are semi colons in the date string the strrep() replaecs them with the hyphen or anything else
av fun.