MATLAB Answers

How can I get a loop to process all ".avi" files in a folder, then produce the corresponding ".txt" and ".png" file?

조회 수: 13(최근 30일)
Tevin Gales
Tevin Gales 2018년 4월 18일
편집: Jan 2021년 3월 8일
I am creating a deep learning CNN with Python and Tensorflow, but the information that will be used in the network will be processed in MATLAB, and so my task is as follows:
I am to use MathWorks' sample code for MotionBasedMultiObjectTracking, but modify it in such a way that as it tracks a moving object, such as a person, in a supplied '.avi' file, it retrieves the (x,y) coordinates of the centroid of the bounding box as it moves in each frame, and writes that information to a '.txt' file. While it does this, it should also print a pattern of white dots onto an all black image, which represents the centroid/(x,y) coordinates as they change across each frame, and save the resulting image as a '.png' file.
I already have this part but that information was supplied just to provide a better understanding of what I'm trying to accomplish overall. Now my problem is that I can't figure out how to write a function or script that can go through all of my .avi files and produce the corresponding x,y coord .txt file and dot pattern .png file. Here is some code:
function MotionBasedMultiObjectTrackingExample()
% create a white image
imageTraj = 255 * ones(480, 640, 'uint8');
blackTraj = 0 * imageTraj;
% create a file to save trajectory data
fileID = fopen('Pattern 1-1.txt','w+');
%imshow(image);
% Create System objects used for reading video, detecting moving objects,
% and displaying the results.
obj = setupSystemObjects();
tracks = initializeTracks(); % Create an empty array of tracks.
nextId = 1; % ID of the next track
% Detect moving objects, and track them across video frames.
while ~isDone(obj.reader)
frame = readFrame();
[centroids, bboxes, mask] = detectObjects(frame);
predictNewLocationsOfTracks();
[assignments, unassignedTracks, unassignedDetections] = ...
detectionToTrackAssignment();
updateAssignedTracks();
updateUnassignedTracks();
deleteLostTracks();
createNewTracks();
displayTrackingResults();
end % end of while
fclose(fileID);
saveas(gcf,'Pattern 1-1.png');
%open the generated image for dilation
BW = imread('Pattern 1-1.png')
%dilation function(strel('dilation type', dilation_strength))
SE = strel('square', 8);
%actually perform the dilation and show the new dilation image
BW2 = imdilate(BW,SE);
figure,imshow(BW2), title('Dilated')
%resize the dilated image
BW3 = imresize(BW2, [64 64]);
figure, imshow(BW3), title('Resized and dilated')
saveas(BW3,'resizedBW3.png');
%%Create System Objects
% Create System objects used for reading the video frames, detecting
% foreground objects, and displaying results.
function obj = setupSystemObjects()
% Initialize Video I/O
% Create objects for reading a video from a file, drawing the tracked
% objects in each frame, and playing the video.
% Create a video file reader.
%obj.reader = vision.VideoFileReader('udcvideo.mp4.mp4');
obj.reader = vision.VideoFileReader('Scenario 1-1.avi');
% Create two video players, one to display the video,
% and one to display the foreground mask.
obj.maskPlayer = vision.VideoPlayer('Position', [740, 400, 700, 400]);
obj.videoPlayer = vision.VideoPlayer('Position', [20, 400, 700, 400]);
% Create System objects for foreground detection and blob analysis
% The foreground detector is used to segment moving objects from
% the background. It outputs a binary mask, where the pixel value
% of 1 corresponds to the foreground and the value of 0 corresponds
% to the background.
obj.detector = vision.ForegroundDetector('NumGaussians', 3, ...
'NumTrainingFrames', 40, 'MinimumBackgroundRatio', 0.7);
% Connected groups of foreground pixels are likely to correspond to moving
% objects. The blob analysis System object is used to find such groups
% (called 'blobs' or 'connected components'), and compute their
% characteristics, such as area, centroid, and the bounding box.
obj.blobAnalyser = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
'AreaOutputPort', true, 'CentroidOutputPort', true, ...
'MinimumBlobArea', 400);
end % end of setupSystemObjects()
My videos are named in the folder as follows: Scenario 1-1 to 1-10, Scenario 2-1 to 2-10.... Scenario 10-1 to 10-10. So there's 100 '.avi' files in the folder. In the setupSystemObjects() function, I supply the video file reader with 'Scenario 1-1.avi'. When I run the program, it runs the process on Scenario 1-1.avi, produces Pattern 1-1.txt, and Pattern 1-1.png, just like I want. The big question is how can I loop it, updating the file name each time so that every time the function is called, it will move to the next file, let's say 'Scenario 1-2.avi' for example, and produce the respective .txt and .png files, all the way until it has finished with the 100 videos in the folder.
I have developed this loop but I'm not sure how to proceed from here: (The comments on the inside below 'code would go here' was just me trying different things.
function FileExample()
d = uigetdir('','Select Input-folder'); %select the input-folder that contains the subfolders
cd(d);
list = dir;
list = list([list.isdir]);
list = list(~ismember({list.name},{'.' '..'}));
l=length(list);
for i=1:l
oldfolder = cd(list(i).name);
% Perform your operation on the files, e.g., if you are working with avi files
files = dir('*.avi');
numberOfFiles = length(files);
for k = 1:numberOfFiles
% code would go here
%
% file name files(k)
% MotionBasedMultiObjectTrackingExample( files(k) )
end
cd(oldfolder);
end
end

답변(2개)

LO
LO 2021년 3월 6일
편집: LO 2021년 3월 8일
clear;
close all;
[logfname, pathname] = uigetfile('*.mat','Pick any AVI file');
cd(pathname);
%make list of AVI files in the folder
file_list = dir ('*.AVI') ; %create a list of AVI files based on folder content
  댓글 수: 2
LO
LO 2021년 3월 6일
thanks Jan, I just copy-pasted from a script of mine without cleaning

댓글을 달려면 로그인하십시오.


Jan
Jan 2021년 3월 6일
편집: Jan 2021년 3월 6일
function FileExample()
Folder = uigetdir('','Select Input-folder');
FileList = dir(fullfile(Folder, '**', '*.avi')); % Select all AVI in folder and subfolders
for iFile = 1:numel(FileList)
file = fullfile(FileList(iFile).folder, FileList(iFile).name);
% code would go here
MotionBasedMultiObjectTrackingExample(file);
end
Now the funtion MotionBasedMultiObjectTrackingExample must accept the file name as input and imprt this file.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by