find correlation images in folders and print result in excel using matlab - matlab

I tried to compare my template image ( image2 ) with image folders names as test* ( test1 , test 2 .... test n) to find correlation between my template image with images from that folder , then print result in that folder then go to next folder test2 .. till test n , thats mean the result of find correlation with each image in folder test1 its print as excel file named ( any name ) store in folder test1 and the content of that excel file as follow :
first row contain the names of images in folder test1 ,
second row contain the correlation result if 0 or 1 after that its jump to next folder test2 ...test3.... etc
the following code i tried long time
xls_sheet = 'Sheet1';
column_range = 'B'; % Initialisation of the column range
srcFolders = dir('D:\test*');
xls_filename = 'result.xls';
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
xlswrite('D:\srcFiles(i)\xls_filename',{srcFolders(folder).name},xls_sheet,folder_range); %Writing the name of the folder in the first row
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
row_range = '2';
srcFolders = dir('D:\');
for folder = 1:length(srcFolders)
srcFolders(folder).fullname = strcat('image:\',srcFolders(folder).name);
end
xlswrite('D:\xlsFile', {srcFolders(:).fullname}, 'Sheet1','A2');
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\act','jpeg');
x = corr2(Image1,Image2);
file_range = strcat(column_range, row_range);
if (x = 0)
xlswrite(xls_filename, {'0'}, xls_sheet, file_range ); %Writing '0' in the second row
else
xlswrite(xls_filename, {'1'}, xls_sheet, file_range ); %Writing '1' in the second row
end
end
row_range = char(row_range + 1); %Moving to the next row
column_range = char(column_range + 1); %Moving to the next column
end
i print names of files in first row , and
my questions how :
1- we can print excel file in each test* folders .
2- how can i repeat this process for all test* folders .
in the result i hope to get excel file in each and every folder in test1 , test 2 ... that contain 1 for corr=1 and 0 for others for all images in that folder.

Related

How to batch combine 2 photos into 1 in python

I'm trying to find a way to batch combine multiple pairs of images into a single image horizontally. I have a folder of hundreds of photos (img01, img02,etc) and I'm trying to merge pairs of these:
img1 + img2 --> img1_2
img 519 + img 520 --> img519_520
The images are 3 x 4 inches and I want to combine them into pairs of horizontal 6 x 4 inch images.
I have found a way to do this for 2 specific photos but I don't know how to loop the code for all the photos in my image folder and save this as a 6x4 photo.
import numpy as np
from PIL import Image
images_list = ['img52.JPG', 'img53.JPG']
imgs = [ Image.open(i) for i in images_list ]
min_img_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
img_merge = np.hstack( (np.asarray( i.resize(min_img_shape,Image.ANTIALIAS) ) for i in imgs )
img_merge = Image.fromarray( img_merge)
img_merge.save( 'Merged image.jpg' )
I am using a Mac OS High Sierra 10.13.4 and python Python 3.6.4.
Any help would be really appreciated!
Source of the above code: https://kanoki.org/2017/07/12/merge-images-with-python/
Update (as of 12 April 2018):
The following should work for a folder with an even number of photos, where the photos are named: img1.jpg, img2.jpg, etc. The script will take a pair of photos (e.g. img1.jpg and img2.jpg) and combine them.
#Note: I run the program in terminal after I change directory to my folder.
import numpy as np
from PIL import Image
images_list = []
for i in range(1,78): #insert last number of photo + 1 (in this case, I have 77 photos)
images_list.append('img'+str(i)+'.JPG')
count = 1;
directory = "path of directory" #change to directory where your photos are
ext = ".jpg"
new_file_name = "vimage-" #change to what you would like to name your photos
new_directory = "path of directory" # change to path of new directory where you want your photos to be saved
for j in range(0,len(images_list),2):
name = new_file_name + str(j) + ext
two_images_list = [images_list[j],images_list[j+1]]
imgs = [ Image.open(i) for i in two_images_list ]
min_img_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_img_shape) ) for i in imgs ) )
imgs_comb = Image.fromarray( imgs_comb)
imgs_comb.save(new_directory+'/'+name )
count +=1
Thanks a lot to #C. Tim for the helpful response!
Update (as of 12 April 2018):
If your images have a name as "img01.JPG", "img42.JPG", this code should work :
you generate all the names and put them in a list. For each pair of images your algorithm converts them into one image and the name of the images created change for every pair.
You must have an even number of images and the images need to be of the same dimension. Thanks a lot to #C. Tim for the helpful response.
# Note: I run the program in terminal after I change directory to my folder.
import numpy as np
from PIL import Image
images_list = []
for i in range(1,78): #insert last number of photo
images_list.append('img'+str(i)+'.JPG')
count = 1;
directory = "path of photos to resize" #change to directory where your photos are
ext = ".jpg"
new_file_name = "vimage-"
new_directory = "path to save in" # change to path of new directory where you want your photos to be saved
for j in range(0,len(images_list),2):
name = new_file_name + str(j) + ext
two_images_list = [images_list[j],images_list[j+1]]
imgs = [ Image.open(i) for i in two_images_list ]
min_img_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_img_shape) ) for i in imgs ) )
imgs_comb = Image.fromarray( imgs_comb)
imgs_comb.save(new_directory+'/'+name )
count +=1

Renaming files in mass in MATLAB

When collecting data, I've currently named my files in the following format:
1_10.mat
Where the number before the underscore is a continent:
1- Africa
2- South America
3- Central America
The second number is the day in that continent the measurement was made on. What I'd like to do is to add the country the measurements were made in onto the end of the filename as well. For example:
1_1 --> 1_10 I want to rename each one to 1_1_Zaire --> 1_10_Zaire
1_11 --> 1_14, I want to rename each one to 1_11_Kenya --> 1_11_Kenya
How could I do this while keeping all the .mat files in the same folder? I'd prefer to use MATLAB for the renaming if possible.
I understand the algorithm will be something like the following:
name a directory with all the .mat files
make a for loop from bound 1 to bound x
concatenate the phrase I want
The only problem is, I don't know how to get the length of the loop, and I don't understand how MATLAB reads files in a directory.
This is what I've tried.
directory = 'C:\place';
for 1 : 9
curName = directory.name;
s = '_Africa';
laterName = (strcat(directory,s)).name;
end
Something like this should get you started:
directory = 'C:\place\';
% Filter the list of files using * as a wildcard.
file = strcat(directory, '*.mat');
% Get a list of files and concatenate them with the directory name.
results = dir(file);
file_name = strcat(directory, '\', num2cell(char(results.name), 2)')';
% The total number of files
nfile = length(file_name)
% Loop through each file.
for i = 1: nfile
curName = file_name{i}
d = textscan(curName, '%3s%f%1s%f');
if (d{2} == 1)
if (1 <= d{4} && d{4} <= 10)
laterName = sprintf('.\\%i_%i_Zaire.mat', d{2}, d{4})
elseif (11 <= d{4} && d{4} <= 14)
laterName = sprintf('.\\%i_%i_Kenya.mat', d{2}, d{4})
end
else
% ...
end
end

dynamically create for loops matlab

I am given a structure with variable names L1dirs, L2dirs...etc all the way up to however many levels the user wants. Each Lxdirs contains a cell array of the names of the directories to be created.
The end result should be the creation of a nested set of directories where each level 1 directory contains all level 2 directories and all level 2 directories contain all level 3 directories, etc. How can I dynamically create this hierarchy?
From the code below, I have already found out through try-catch statements how many levels the user specified.
Now given that we know how many levels the user specified, how can we generate a list of all the unique filepath combinations? The end result should be a column cell array of m paths where mis the number of L1 directories times the number of L2 directories times.....times the number of Lx directories.
Can MATLAB do this? I attempted to use eval() by creating a dynamically created string macro, but eval doesn't like the use of the end statement when trying to dynamically nest for loops. Is there another way?
Here is a sample piece of code of what I have so far:
Main Code
userinputs.L1dirs = {'Level 1 Dir 1';
'Level 1 Dir 2';
'Level 1 Dir 3'};
userinputs.L2dirs = {'Level 2 Dir 1';
'Level 2 Dir 2';
'Level 2 Dir 3'};
userinputs.L3dirs = {'Level 3 Dir 1';
'Level 3 Dir 2';
'level 3 Dir 3'};
userinputs.top_level_dir = strcat(pwd,'\Results\');
pathlist1 = check_results_dirs(userinputs)
userinputs.L4dirs = {'Level 4 Dir 1';
'Level 4 Dir 2'};
userinputs.top_level_dir = strcat(pwd,'\Results 2\');
pathlist2 = check_results_dirs(userinputs)
Support Function
function pathlist = check_results_dirs(inputdata)
%{
This function checks if the file directory exists in the top level
directory as specified by the inputs structure. If the directory already
exists, then it checks whether these files are to be overwritten or not.
This function dynamically checks how many levels of directories the user
specified.
Inputs
inputdata - structure containing the following variable names
inputdata.LXdirs - X is an integer value. Variable(s) contain cell
arrays of directory names
inputdata.top_level_dir - top level destination directory to
create this file structure. If this folder does not exist, it will be
created.
%}
%check if top level directory exists
if ~exist(inputdata.top_level_dir,'file')
mkdir(inputdata.top_level_dir);
end
%determine how many directory levels there are as determined by the user
numDirLevels = 1;
numDirsPerLevel = [];
moreDirsFlag = 1;
while moreDirsFlag
try
eval(sprintf('temp = inputdata.L%idirs;',numDirLevels));
numDirsPerLevel = [numDirsPerLevel; length(temp)];
numDirLevels = numDirLevels + 1;
catch err
if strcmp(err.identifier,'MATLAB:nonExistentField')
%no more directory levels
numDirLevels = numDirLevels - 1;
moreDirsFlag = 0;
else
rethrow(err);
end
end
end
numUniqueDirs = prod(numDirsPerLevel);
%Generate Path list
beginstr = '';
midstr = 'pathlist{numUniqueDirs} = strcat(';
endstr = '';
for ii = 1:numDirsPerLevel
beginstr = strcat(beginstr,sprintf('for x%i=1:numDirsPerLevel(%i) ',ii,ii));
midstr = strcat(midstr,sprintf('inputdata.L%idirs(x%i),''\\'',',ii,ii));
endstr = strcat(' end ',endstr);
end
midstr = strcat(midstr,''''');');
evalstr = ' numUniqueDirs = numUniqueDirs+1;'
midstr = strcat(midstr,evalstr);
evalstr = 'numUniqueDirs = 1; '
beginstr = strcat(evalstr,beginstr);
eval(strcat(beginstr,midstr,endstr)); %error is thrown here due to an illegal
%use of 'end'. Can I not
%use for loops using eval?
%debug statements
disp(beginstr)
disp(midstr)
disp(endstr)
end
Note how in the main code the function is called twice. Once calls it to make three levels of directories another call is to make four levels of directories. The output pathlist should contain numL1dirs times numL2dirs times .... times numLxdirs so for the first example it should create 27 distinct directories such that each level 1 dir contains all three level 2 dirs and each level 2 dir contains all three level 3 dirs. For the second example, pathlist should contain 54 unique directory paths.
Well the reason why you struggled so much is probably your attachment to eval. You need to really limit the use of that to a strict minimum ... ideally never. I can see why you thought you had to resort to it (your dynamic field/variable names) but fortunately Matlab gave us a few tools to overcome that.
You should have a good look at the Dynamic field names functionalities from Matlab. This will probably be of great use given your style of programming, and use it as much as you can to avoid any use of the evil eval.
Once you use this. Do a recursive call to generate a list of strings representing all the paths of the folders to generate, then mkdir them and you're done.
function pathList = Generate_PathList(userinputs)
%% // check if top level directory exists
if ~exist(userinputs.top_level_dir,'dir')
mkdir(userinputs.top_level_dir);
end
%% // determine how many directory levels there are
fnames = fieldnames(userinputs) ;
maxDirLevel = 1 ;
for iField = 1:numel(fnames)
lvlDir = sscanf(fnames{iField},'L%idirs') ;
if lvlDir > maxDirLevel
maxDirLevel = lvlDir ;
end
end
%% // Generate string list
pathList = { userinputs.top_level_dir } ;
for iLvl = 1:maxDirLevel % // loop on all directory level
dirLevelName = ['L' num2str(iLvl) 'dirs'] ;
pathList = addPathToList( pathList , userinputs.(dirLevelName) ) ;
end
%% // Generate the directories
for iDir = 1:numel(pathList)
mkdir( pathList{iDir} ) ;
end
%% // Helper function called recursively
function pathListOut = addPathToList( pathList , dirNames )
nTop = numel(pathList) ;
nLow = numel(dirNames) ;
pathListOut = cell( nTop*nLow , 1 ) ;
iPath = 0 ;
for iTopDir = 1:nTop
for iLowDir = 1:nLow
iPath = iPath + 1 ;
pathListOut{iPath} = [pathList{iTopDir} '\' dirNames{iLowDir}] ;
end
end
You can call this function the same way you used to call your initial function:
userinputs.top_level_dir = strcat(pwd,'\Results');
pathList = Generate_PathList(userinputs)
userinputs.L4dirs = {'Level 4 Dir 1';
'Level 4 Dir 2'};
userinputs.top_level_dir = strcat(pwd,'\Results 2');
pathList = Generate_PathList(userinputs)
Will create your 27 and respectively 54 unique folders.
Just note that I removed the last '\' in your top level folder definition (to be consistent with the folder path generation used later on ...)

Odd numbering of files from one folder to other in matlab

Files present in one folder:
1 copy(1).jpg,
1 copy(2).jpg
.......
.......
.......
1 copy(800)
Odd numbering of files and save it in other folder.Desired output shown below:
1.jpg,
3.jpg,
5.jpg
....
....
....
799.jpg
Source code i tried:
a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\';
A =dir( fullfile(a, '*.jpg') );
fileNames = { A.name };
for iFile = 1 : numel( A )
newName = fullfile(a, sprintf( '%d.jpg',iFile+2) );
movefile( fullfile(a, fileNames{ iFile }), newName );
end
But i cant able to get desired output.So what will be the solution?
Don't rename the files, just move them to the new directory after checking if they had an odd number in their file name:
a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\';
destination = a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\Odd\';
A =dir( fullfile(a, '*.jpg') );
fileNames = { A.name };
for iFile = 1 : numel( A )
[~,name] = fileparts(fileNames{ iFile }); %// This part might not be necessary if fileNames{ iFile } is just the file name without the directory. In that case rather use name=fileNames{ iFile };
%// Extract the number from the file name
filenum = str2num(name(8:end-4));
%// Check if the number is odd
if mod(filenum,2) == 1
movefile(fullfile(a, fileNames{ iFile }), fullfile(destination, fileNames{ iFile }));
end
end

Read with order files in subfolders in matlab

I've got a folder which contains subfolders with text files. I want to read those file with the same order as they are in the subfolders. I've got a problem with that. I use the following matlab code:
outNames = {};
k=1;
feature = zeros(619,85);
fileN = cell(619,1);
for i=1:length(nameFolds)
dirList = dir(strcat(path, num2str(cell2mat(nameFolds(i,1)))));
names = {dirList.name};
outNames = {};
for j=1:numel(names)
name = names{j};
if ~isequal(name,'.') && ~isequal(name,'..')
[~,name] = fileparts(names{j});
outNames{end+1} = name;
fileName = strcat(path, num2str(cell2mat(nameFolds(i,1))), '\', name, '.descr' );
feature(k,:) = textread(fileName);
fileN{k} = [fileName num2str(k)];
k= k+1;
end
end
end
In one subfolder I've got the above text file names:
AnimalPrint_tiger_test_01.descr
AnimalPrint_tiger_test_02.descr
AnimalPrint_tiger_test_03.descr
AnimalPrint_tiger_test_04.descr
AnimalPrint_tiger_test_05.descr
AnimalPrint_tiger_test_06.descr
AnimalPrint_tiger_test_07.descr
AnimalPrint_tiger_test_08.descr
AnimalPrint_tiger_test_09.descr
AnimalPrint_tiger_test_10.descr
AnimalPrint_tiger_test_11.descr
AnimalPrint_tiger_test_12.descr
AnimalPrint_tiger_test_13.descr
AnimalPrint_tiger_test_14.descr
AnimalPrint_tiger_test_15.descr
AnimalPrint_zebra_test_1.descr
AnimalPrint_zebra_test_2.descr
AnimalPrint_zebra_test_3.descr
AnimalPrint_zebra_test_4.descr
AnimalPrint_zebra_test_5.descr
AnimalPrint_zebra_test_12.descr
But it seems that it reads first the AnimalPrint_zebra_test_12.descr and after the AnimalPrint_zebra_test_1.descr and the rest. Any idea why this happens?
dir sorts the files according to their names, for instance
test_1
test_12 % 1 followed by 2
test_2
test_3
You may want to build your own order with ['test_' num2str(variable) '.descr'] that concatenates test_ with an incrementing variable.