Matlab : Open previously saved figures and save as - matlab

I'm writing a Matlab code which plots and saves figures as png and eps.
h = figure(3);
plot(x,y)
xlabel('x'); ylabel('y');
FileName = sprintf('FileName.eps');
print(h,'-depsc', '-loose', FileName);
FileName = sprintf('FileName.png);
print(clhis,'-dpng', '-loose', FileName);
close(h)
I would like to just save them as FileName.fig for later process.
The function/script I would like to create would read all *.fig in current dir and save them as defined function.
Here is a pseudo function... But I'm not sure how to make it work properly!
function figureconvert(ext) % NOT WORKING! Just a mock up!
ext = 'eps';
Vector = READ ALL FIGS IN FOLDER;
for i = 1:length(Vector)
h = load Vector(i)
FileName = sprintf('FileName.%s',ext);
% print(h,'-d%sc', '-loose', FileName); ??
close(h)
end
end

I found a solution how to do this. Here is my function if someone else will need such function.
Just write:
figureconvert('png') or figureconvert('eps')
to convert *.fig to *.png or *.eps respectively.
function figureconvert(ext)
Files = dir('*.fig');
ext = ['.',ext]; ext = strrep(ext,'..','.');
for i = 1:length(Files)
figname = Files(i,1).name;
h = openfig(figname);
FigName = strrep(figname,'.fig',ext);
if strcmp(ext,'.eps')
print(h,'-depsc', '-loose', FigName);
elseif strcmp(ext,'.png')
print(h,'-dpng', '-loose', FigName);
end
close(h)
end
end

Related

Matlab - Multiple Plots in one Figure

I have a question about plots and subplots. I am iterating over some data and I am trying to get everything into a plot. It worked that every plot got written into one plot with hold on and figure but now I have to fit in regression lines. Therefore I want to plot everythiong into one figure but into different plots. This doesnt work as my plot looks a little bit weird.
My problem now is, that I cant find real helpful things on how to manage those plots other than using uicontrol. But I have never ever used uicontrol and I canĀ“t find enogh documentation to use it properly. I found this code:
figure(1)
panel1 = uipanel('Parent',1);
panel2 = uipanel('Parent',panel1);
set(panel1,'Position',[0 0 .99 1]);
set(panel2,'Position',[-1 0 2 1]);
set(gca,'Parent',panel2);
h = image; % <- Code for my own image goes here
s = uicontrol('Style','Slider','Parent',1,...
'Units','normalized','Position',[0 0 1 .025],...
'Value',1,'Callback',{#slider_callback1,panel2});
but all I get is a callback Problem. I dont know how to switch from a horizontal to a vertikal scrollbar and how to get my plots in there. The code manage it to write into the figure but in a very strange way that results in a similiar way as the subplotting everything.
I hope you can help me as good as always!
PS: This is my current code thats working (picture of the plot after it)
%% Clear Workspace
clc, clear all, close all; %
S = {} ;
F = [] ;
figure, hold on ;
%% Specify working directory
myFolder = '/home/k/karkarov92/Documents/Daten Igor/Zwick';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
%% Start Import from Mathilda aka. Z20
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.TXT'); % Change to whatever pattern needed.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
str = baseFileName;
level = wildcardPattern + "NIE_TOM_1_" ; % Name of the Pattern before the Name of the Sample
pat = asManyOfPattern(level);
str = extractAfter(str,pat);
Sample = erase(str,".TXT");
disp(Sample)
delimiterIn = ' '; %Extract thickness out of headers
headerlinesIn = 9;
G = importdata(fullFileName,delimiterIn,headerlinesIn);
G(3);
H = split(G(3));
K = H(2);
thickness = str2double(K)/100 ;
%read Table and extract Units
A = readtable(fullFileName,'decimal', ','); % without decimal and "," data import not with the right value wrong unit
Units = A(1,:);
A(1,:) = []; %units extracted and then stripped from table
%table = A(1:4,:); table output test
B = table2array(A); %change data from table to array
%disp(B(1:4,:)) ; %Array output test
strain = (B(:,2)- B(1,2)) / B(1,2); %strain calculated and stored in vector strain
stretch = strain +1 ; %stretch calculated and stored in vector strain
crossSection = 5. * thickness ; %calculate cauchy stress and cross section
cauchyStress = ((B(1:end,3).*stretch) / crossSection ) * 1000 ; %[GPa]
M = max(B) ; %exctract maxForce
maxForce = M(1,3) ;
F(end+1) = maxForce ;
S{k} = Sample ;
plot(stretch,cauchyStress)
xlabel('Stretch')
ylabel('Cauchy Stress')
title('Linear Regression for Modulus')
grid on
end

Read images from sub folders and save into another folder

I have a code here.
start_path = fullfile(matlabroot, '\toolbox\images\imdemos');
% Ask user to confirm or change.
topLevelFolder = uigetdir(start_path);
if topLevelFolder == 0
return;
end
% Get list of all subfolders.
allSubFolders = genpath(topLevelFolder);
% Parse into a cell array.
remain = allSubFolders;
listOfFolderNames = {};
while true
[singleSubFolder, remain] = strtok(remain, ';');
if isempty(singleSubFolder)
break;
end
listOfFolderNames = [listOfFolderNames singleSubFolder];
end
numberOfFolders = length(listOfFolderNames)
% Process all image files in those folders.
for k = 1 : numberOfFolders
% Get this folder and print it out.
thisFolder = listOfFolderNames{k};
fprintf('Processing folder %s\n', thisFolder);
% Get PNG files.
filePattern = sprintf('%s/*.png', thisFolder);
baseFileNames = dir(filePattern);
% Add on TIF files.
filePattern = sprintf('%s/*.tif', thisFolder);
baseFileNames = [baseFileNames; dir(filePattern)];
% Add on JPG files.
filePattern = sprintf('%s/*.jpg', thisFolder);
baseFileNames = [baseFileNames; dir(filePattern)];
numberOfImageFiles = length(baseFileNames);
% Now we have a list of all files in this folder.
if numberOfImageFiles >= 1
% Go through all those image files.
for f = 1 : numberOfImageFiles
fullFileName = fullfile(thisFolder, baseFileNames(f).name);
pathname = strcat('C:\\xampp\\htdocs\\PACS_Client\\cbir_matlab\\ano\\');
outputBaseFileName = sprintf('%3.3d.jpg',f);
outputFullFileName = fullfile(pathname, outputBaseFileName);
fprintf('Processing image file %s\n', fullFileName);
im=imread(fullFileName);
imshow(im);
data = im;
imwrite(data,[pathname,outputBaseFileName]);
end
else
fprintf(' Folder %s has no image files in it.\n', thisFolder);
end
end
i tried to save all the images from sub folders into another folder.But could not get all the images.Only few numbers of images are saved.I want to save all the images.can anyone help me with this code?
i updated your code a bit please check if this works for you. One issue being your base file name always is '%3.3d.jpg' so every picture will be a '.jpg' even if its not. Also you are loading and showing images, but you only need to copy them, so you can go for copyfile. 3rd you always setting every image 001.jpg which will overwrite the the last 001.jpg from the previous folder. you have to add the number so the next folder starts with higher numbers.
start_path = fullfile(matlabroot, '\toolbox\images\imdemos');
% Ask user to confirm or change.
topLevelFolder = uigetdir(start_path);
if topLevelFolder == 0
return;
end
%dir where everything should go. if the destination is not the
%topLevelFolder
%destinationpath = strcat('D:\\pics\\');
destinationpath = topLevelFolder;
% Get list of all subfolders.
allSubFolders = genpath(topLevelFolder);
% Parse into a cell array.
remain = allSubFolders;
listOfFolderNames = {};
%while true
% [singleSubFolder, remain] = strtok(remain, ';');
% if isempty(singleSubFolder)
% break;
% end
% listOfFolderNames = [listOfFolderNames singleSubFolder];
%end
%your while worked fine, but try to avoid 'while true' with break
for i=1:sum(strfind(allSubFolders,';'))
[singleSubFolder, remain] = strtok(remain, ';');
listOfFolderNames = [listOfFolderNames singleSubFolder];
end
numberOfFolders = length(listOfFolderNames)
%set inital count
picturecount=0;
% Process all image files in those folders.
for k = 1 : numberOfFolders
% Get this folder and print it out.
thisFolder = listOfFolderNames{k};
fprintf('Processing folder %s\n', thisFolder);
% Get PNG files.
filePattern = sprintf('%s/*.png', thisFolder);
baseFileNames = dir(filePattern);
% Add on TIF files.
filePattern = sprintf('%s/*.tif', thisFolder);
baseFileNames = [baseFileNames; dir(filePattern)];
% Add on JPG files.
filePattern = sprintf('%s/*.jpg', thisFolder);
baseFileNames = [baseFileNames; dir(filePattern)];
numberOfImageFiles = length(baseFileNames);
% Now we have a list of all files in this folder.
if numberOfImageFiles >= 1
% Go through all those image files.
for f = 1 : numberOfImageFiles
fullFileName = fullfile(thisFolder, baseFileNames(f).name);
[~,~,ext] = fileparts(baseFileNames(f).name); %get extension
outputBaseFileName = sprintf(['%3.3d' ext],f+picturecount);%create name based on picturecount
outputFullFileName = fullfile(destinationpath, outputBaseFileName);
%fprintf('Processing image file %s\n', fullFileName);
%im=imread(fullFileName);
%imshow(im);
%data = im;
%imwrite(data,[pathname,outputBaseFileName]);
%you dont need it in matlab just copy the file
copyfile(fullFileName,outputFullFileName);
end
picturecount=picturecount+numberOfImageFiles;%set picturecount for next k
else
fprintf(' Folder %s has no image files in it.\n', thisFolder);
end
end
The problem is in baseFileNames = dir(filePattern), where you reset the list each time the loop is on a new folder. This is why at the end you will only have the images of the last folder. Simply add baseFileNames = [] just before the for loop and then replace baseFileNames = dir(filePattern) with baseFileNames = [baseFileNames; dir(filePattern)].

Accessing multiple folder matlab and store in same mat

I am newbie to Matlab. I have code like below. How to read multiple folder. I know by using loop but somehow I google it I cannot find it. Also,what i have wrote below is for myA folder. How to put featureVector in same mat AllTrain for myA, myB, myC? The folder contain of image.
clear all;
clc;
trainlabel = [];
featureVector = [];
AllTrain = [];
% Specify the folder
myA = 'C:\Users\NotComplex\a';
myB = 'C:\Users\NotComplex\b';
myC = 'C:\Users\NotComplex\c';
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myA, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now imread the file
imageArray = imread(fullFileName);
imageEdge = edge(imageArray, 'canny', 0.4);
a_inv_mom = Hu_Moments(imageEdge);
format short
a_inv_mom_normal = -sign(a_inv_mom).*(log10(abs(a_inv_mom)));
featureVector = cat(1,a_inv_mom_normal);
AllTrain(k,:) = [featureVector k];
% imshow(imageEdge); % Display image.
drawnow % Force display to update immediately.
end
To be compact:
folderCell = {'C:\Users\NotComplex\a', 'C:\Users\NotComplex\b', 'C:\Users\NotComplex\c'};
theFiles = cellfun(#(x) fullfile(x, '*.pgm'), folderCell, 'UniformOutput', false);
Then you can continue with your loop, theFiles will contain all of the .pgm files from all of the three directories

Error using fread and imageparser

Hello when l run the code above l got this error . l don't where is the error ,my codes (.m) and training examples are in the same working directory.
Error using fread
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in MNISTParser (line 3)
magic_number = fread(fp,1,'uint32',0,'b');
Error in MNIST_gen (line 2)
train_labels = MNISTParser('./MNIST/train-labels-idx1-ubyte');
MNIST_gen.m
clear
**train_labels = MNISTParser('./MNIST/train-labels-idx1-ubyte');**
train_images = MNISTParser('./MNIST/train-images-idx3-ubyte');
test_labels = MNISTParser('./MNIST/t10k-labels-idx1-ubyte');
test_images = MNISTParser('./MNIST/t10k-images-idx3-ubyte');
test_item_number = length(test_labels);
train_item_number = length(train_labels);
image_scale = size(test_images,2);
test_images_unfold = reshape(test_images,test_item_number,image_scale^2)';
test_labels_unfold = full(ind2vec(test_labels'+1));
train_images_unfold = reshape(train_images,train_item_number,image_scale^2)';
train_labels_unfold = full(ind2vec(train_labels'+1));
save MNIST.mat;
colormap(gray);
axis off
axis image
%show an image of a digit in test samples
for i=1:1
j=randi(length(test_labels),1);
image(reshape(255-test_images(j,:,:),28,28));
title(sprintf('%d',test_labels(j)));
pause(1);
image(reshape(test_images_unfold(:,j),28,28));
title(vec2ind(test_labels_unfold(:,j))-1);
pause(1);
end
%show an image of a digit in train samples
for i=1:1
j=randi(length(train_labels),1);
image(reshape(255-train_images(j,:,:),28,28));
title(sprintf('%d',train_labels(j)));
pause(1);
image(reshape(train_images_unfold(:,j),28,28));
title(vec2ind(train_labels_unfold(:,j))-1);
pause(1);
end
MNISTParser.m
function res = MNISTParser(filename)
fp = fopen(filename,'r');
**magic_number = fread(fp,1,'uint32',0,'b');**
items_number = fread(fp,1,'uint32',0,'b');
if 2049==magic_number
res = fread(fp,items_number,'uint8',0,'b');
else
if 2051==magic_number
img_rows = fread(fp,1,'uint32',0,'b');
img_cols = fread(fp,1,'uint32',0,'b');
res = zeros(items_number,img_rows,img_cols);
for i=1:items_number
res(i,:,:) = fread(fp,[img_cols,img_rows],'uint8',0,'b')';
end
else
error('wrong magic number');
end
end
fclose(fp);
end
Thanks for helps
l find the mistake. it is related to the extension of the files.
here is the instruction that has helped me to find out my mistake [fp,msg] = fopen(filename,'r');
if fp<1, error([msg ' File: ' filename]);

saving outputs from a loop in Matlab in different folders

I am using the codes below which save the output images in the same directory as is the m-file. I am trying to automate to save the output images in different folders with the folder name same as the 'file' name.
clear all;
files = dir('*.dat');
for k = 1:length(files);
filename = files(k).name;
data1 = fopen(filename,'r');
data2 = textscan(data1, '%f%f','headerlines',1,'CollectOutput',1);
data = data2{:,1};
x = data(:,1);
y = data(:,2);
plot(x, y);
[pathstr, name, ext] = fileparts(filename);
temp = ['fig', num2str(k), '.eps'];
print(gcf, '-depsc', temp);
fclose(data1);
end
Any help will be very much appreciated.
You have to create a subfolder (named after your filename), then print in this folder.
folderName = filename;
mkdir(folderName);
print( gcf , [folderName '/' filename] ); %or use `filesep` function to replace /