Reading files frame by frame - matlab

I have a folder containing .ply files. I want to read them and plot them like an animation. Initially i am trying to read the files and plot individually using the following code:
testfiledir = 'Files\';
plyfiles = dir(fullfile(testfiledir, '*.ply'));
for k=1:length(plyfiles)
FileNames = plyfiles(k).name;
plys=pcread(FileNames);
pcshow(plys)
end
But while running the script i get the error:
Error using pcread (line 51)
File "val0.ply" does not exist.
Error in read_pcd (line 6)
plys=pcread(FileNames);
val0.ply is one my first frame which is read in the variable 'plyfiles'
Where am I making mistake?

Use a datastore it is much easier and will keep track of everything for you. E.g.
ds = fileDatastore("Files/","ReadFcn",#pcread,"FileExtensions",".ply");
then you can read the files from it using read or readall, e.g.
while hasdata(ds)
plys = read(ds);
pcshow(plys)
end
It is slightly slower than if you can make the optimal implementation, but I prefer it big-time for its ease.

Related

Loading file in MatLab

Attempting to follow this tutorial https://www.mathworks.com/help/vision/ref/objectdetectortrainingdata.html, I have aerial photos of parking lots in which I want cars to automatically be counted by the program. (If I am going in the wrong direction or there is an easier solution please let me know!).
My Error:
Warning: Variable 'carsGroundTruth' not found.
In carDetection (line 3)
My Code:
imageDir = fullfile(matlabroot, 'toolbox', 'vision', 'visiondata', 'carImages');
addpath(imageDir);
load('cars.mat','carsGroundTruth')
Why won't cars.mat load? I have tried putting it in the MATLAB file within Documents, and also the imageDir referenced in line 1.

Matlab: labeling images stored in a single file based on image name

I was assigned a matlab assignment where I was given 25000 pictures of cats and dogs all stored in one folder. My question is how can I use the imagedatastore function on matlab to store these files into one single variable containing two labels (cats and dogs). Each image stored in the file follow the following format:
cat.1.png,
cat.2.png,
.....,
cat.N.png,
dog.1.png,
dog.2.png,
.....,
dog.N.png,
Ideally I think labeling them based on image name would probably be the best approach to this. How ever I've tired doing this using various implementations methods but I keep failing. Any advice on this would be greatly appreciated!
The steps for both image data stores are the same:
Find all the image files with a matching name with dir.
Rebuild the full path to these files with fullfile.
Create the image data store with the files.
My code assumes that you are running the script in the same folder in which images are located. Here is the code:
cats = dir('cat.*.png');
files_cats = fullfile({cats.folder}.', {cats.name}.');
imds_cats = imageDatastore(files_cats);
dogs = dir('dog.*.png');
files_dogs = fullfile({dogs.folder}.', {dogs.name}.');
imds_dogs = imageDatastore(files_dogs);
You could also use the short path:
imds_cats = imageDatastore('cat.*.png');
imds_dogs = imageDatastore('dog.*.png');
If you want to use a single image data store and split files into categories within it (without using folder names, since all your files seem to be located in the same directory):
cats = dir('cat.*.png');
cats_labs = repmat({'Cat'},numel(cats),1);
dogs = dir('dog.*.png');
dogs_labs = repmat({'Dog'},numel(dogs),1);
labs = [cats_labs; dogs_labs];
imds = imageDatastore({'cat.*.png' 'dog.*.png'},'Labels',labs);

Matfile isn't loading the structure's field names

Background
I encountered some strange behaviour with the function "matfile" in Matlab 2016b - not sure what's going on, and I can't replicate it or create a test case.
I have a structure, which I saved to a server, like so:
PathToFile='ServerPath\My Documents\MyProj\testMatF.mat';
save(PathToFile,'-struct','myStruct'); %I tried the -v7.3 flag
Problem
Then I read it in with:
m1=matfile(PathToFile);
On other, very similar structs, I can do:
myFields=fieldnames(m1);
But for this one file I can't, all I get is the auto "Properties" field.
What I've tried
myFields=who(m1) - gives me list of fieldnames... sometimes. I don't know the who function well, but it seems, if I intersperse who m1 then myFields=who(m1) it works.
Explicitly typing m1.TheFieldName, works.
Moving the file to a location on the comp, like C:\Data\. Then using fieldnames works.
Using load, works.
Does it have to do with the server access, corrupted file, matfile properties? One other weird thing is some of my .m files in this particular folder, when I try to open them results in: Does not exist, when clearly it does, since I click on it and can use the run function with it... Additional: Windows 7. Recently updated license.
Please let me know what info you can use to help out. Either to create a new file that will work, or fix the problem with the current file. Thanks.
EDIT
Example output in my command window - seemingly incomprehensible...
m1=matfile(fullfile(projPath,'NexusMarkersProcessed.mat'),'Writable',false)
m1 =
matlab.io.MatFile
Properties:
Properties.Source: '\bontempi.medicine.utorad.utoronto.ca\home\PT\zabjeklab3\My
Documents\Data\Active Projects\JC_Hip\FL1502\FL1502\Patient
Classification 2\NexusMarkersProcessed.mat'
Properties.Writable: false
Methods
K>> m1.Properties.Source
ans =
\bontempi.medicine.utorad.utoronto.ca\home\PT\zabjeklab3\My
Documents\Data\Active Projects\JC_Hip\FL1502\FL1502\Patient
Classification 2\NexusMarkersProcessed.mat
K>> java.io.File(m1.Properties.Source).exists()
ans =
logical
0
Pause to paste in this window... go back:
java.io.File(m1.Properties.Source).exists()
ans =
logical
1
K>> who(m1)
Your variables are:
Patient10 Patient5 Patient9 Patient11 Patient6 Patient3
Patient7
K>> who(m1) K>> who(m1) K>>
java.io.File(m1.Properties.Source).exists()
ans =
logical
0
K>>
So it sometimes finds the file, and can read it in. Othertimes it cannot - is this to do with the fact that it's on a network drive?
Any help is appreciated.
This issue is caused by accessing a file on a network drive. One workaround is to copy the file to a local drive (C: is used), and then use matfile, use the result as needed, then replace the network drive file, and delete the local file, to return things to their original state. Some research made me realize things are slower than they need to be if any files, even the .m ones, are on the network. Here's a function that worked:
function [m,noData]=safeMatFile(FilePath,safeFilePath)
%FilePath: absolute path to where the file is on the network
%safeFilePath: absolute path to where the file will be temporarily copied locally, C://
%safeDir='C:\Data';
%safeFold='tempFolder12345679';
%[~,tempDir,~]=mkdir(safeDir,safeFold);
%safeFilePath=fullfile(safeDir,safeFold,FileName);
noData=0;
dirFile=dir(FilePath);
if (length(dirFile) == 1) && ~(dirFile.isdir)%OR java below OR exist(forceFilePath,'file')==2
%if there is a file, make a temp folder on the C drive
if ~(java.io.File(safeFilePath).exists() && java.io.File(safeFilePath).isFile()) %ensure file doesn't exist, check dir too: || isempty(tempFolder)
copyfile(FilePath, safeFilePath);%moves existing file to backup folder
else
warning('SKIPPING (%s) - an old file of the same name was there, delete it!\n',safeFilePath);
return
end
%Load the temp local file into matlab
m=matfile(safeFilePath,'Writable',true);
else
m=[];
noData=1;
end
end
Then do stuff with m... and at the end:
function overwriteOldFiles()
if (java.io.File(safeFilePath).exists() && java.io.File(safeFilePath).isFile())
java.io.File(FilePath).delete();
java.io.File(safeFilePath).renameTo(java.io.File(FilePath));
end
end
and
function deleteTempFiles()
if (java.io.File(safeFilePath).exists() && java.io.File(safeFilePath).isFile())
java.io.File(safeFilePath).delete();
end
end
... Then rmdir if necessary.
Note, I tried different ways of checking if the file exists (I think the first is fastest and most reliable):
dirFile=dir(FilePath); if (length(dirFile) == 1) && ~(dirFile.isdir)
if (java.io.File(FilePath).exists() && java.io.File(FilePath).isFile())
if exist(FilePath,'file')==2

How can I change the name of the file being saved without editing the code? MatLab

I am working on an experiment that take a lot of data samples and save it to different video files. For example, I take data and save it to a file called "slowmotion.avi" and then I take another set of data and save it to another file called "normalspeed.avi".
I am trying to find a way that I could change the name of file being saved without editing the code. The way I am using right now makes me have to open the code and change the name of the file directory within the code and then save the code. I want to make it a lot faster and easier to use.
I have tried the following code to fix this problem but it doesn't work.
graph=input('Graph of experiment: ');
vidObj = VideoWriter('%3.1f.avi\n',graph);
.....
Hope I didn't confuse you.
A possible solution:
graph=input('Graph of experiment: ','s');
vidObj = VideoWriter([graph,'.avi']);
The 's' in the input() function indicates that the expected input is a string, and [graph,'.avi'] simply concatenates both strings.

error using save can't write file

I have got this really strange error in matlab. When I try to run the command
save(fullfile('filepath','filename'),'var','-v7');
I get the error message,
error using save can't write file
but when I try
save(fullfile('filepath','filename'),'var','-v7.3');
everything works fine. The the variable takes some space on the workspace, 165MB, but the I would guess that the size should not be an issue here. Does anyone know why it does not work to save in v7?
For the one that want to confirm the size of the variable, I will add the whos information,
Name Size Bytes Class Attributes
myName 1x1 173081921 struct
BR/ Patrik
EDIT
The variable I try to save is a struct with plenty of fields. I have tried to save a 3 dimensional matrix of size 800 mb, which went through without problems.
This is not an exact match to your problem, but I received the same error message when trying to save to -v6 format. Matlab is supposed to issue an error when a variable type or size is not supported:
help save
...
If any data items require features that the specified version does not support, MATLAB does not save those items and issues a warning. You cannot specify a version later than your version of MATLAB software.
Matlab's error checking seems to not be perfect, because there are certain situations (dependent on Matlab version and the particular variable type) that just fail all together with this not so helpful error message:
Error using save
Can't write file filename.mat.
For example, saving a string with certain unicode characters with the '-v6' option in Matlab r2015b in Linux produces the error, but Matlab r2016a in Windows does not. This is the output from my Matlab r2015b session:
>> A=char(double(65533))
A =
?
>> save('filename.mat','-v6','A')
Error using save
Can't write file filename.mat.
Without having your specific variable to test with, but seeing that the error messages match, I suggest removing parts of your data structure until it will save in order to isolate the variable that is causing it to fail.