compare multi images with all images in referenced folders using matlab - excel

I have some reference image (I'll call this images as Ref\animal.jpg', 'Ref\food.jpg', 'Ref\gon.jpg ... etc ). Then in each folder i want to compare Image1, Image2, ..., ImageN to each referenced image . I want to summarize the results of the comparison by writing to an Excel file (which has the same name as the folder) (in A1) 'Image 1 = ok', (in B1) 'Image 2 = no', ..., (in the Nth row, 1st column) 'Image N = ok'.
i got the following error , when i use single image its working well but multi images in reference images ( second line ) i got cellfun error .
Error using cellfun
Input #2 expected to be a cell array, was double instead.
any one please can correct the following code ??
%The base file path
path = 'D:';
% Relative reference to reference images
ImageRefLocations = {'Ref\RefI1.jpg', 'Ref\RefI2.png', 'Ref\RefI3.jpg'};
%Base Image location
baseImage = fullfile(path, ImageRefLocations(:));
%The pattern used to choose the folders
folderPattern = 'folder*';
%The image extension
[~, ~, ext] = unique(cellfun(#(f) fileparts(f), baseImage, 'uni', 0));
%The excel extension
ExcelExt = '.xlsx';
msg = {' = no'; ' = ok'};
i0 = cellfun(#(f) imread(f), baseImage, 'uni', 0);
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
isDir = [srcFolders.isdir];
srcFolders = {srcFolders(isDir).name}';
PathedFolders = fullfile(path, srcFolders);
excelFiles = fullfile(path, strcat(srcFolders, ExcelExt));
for i = 1:length(PathedFolders)
f = PathedFolders{i};
after this line i got error ...
Error using cellfun
Input #2 expected to be a cell array, was double instead.
Images = cellfun(#(x) dir(fullfile(f, ['*', x])), ext, 'uni', 0);
Images = vertcat(Images{:});
if isempty(Images)
continue
end
Images = {Images.name}';
[~, ImageNames, ~] = cellfun(#(x) fileparts(x), Images, 'uni', 0);
ImageList = fullfile(f, Images);
match = zeros(size(ImageList));
for j = 1:length(ImageList)
image = imread(ImageList{j});
for k = 1:length(i0)
if ~all(size(image) == size(i0{k}))
continue
end
match(j) = all(image(:) == i0{k}(:));
if match(j)
continue
end
end
end
matchMessage = strcat(Images, msg(match + 1));
xlswrite(excelFiles{i}, matchMessage)
end

Related

How to merge cells without losting data in libreoffice-calc?

Launch libreoffice-calc:
soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
Launch python shell to write data into the calc:
import uno
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
svcmgr = context.ServiceManager
desktop = svcmgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
oDoc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
oSheet = oDoc.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:C3")
Write data into oRange.
oRange.setDataArray((('a1','a2','a3'),('b1','b2','b3'),('c1','c2','c3'),))
The calc's appearance now:
I want to merge all data in oRange and format it with vertical and horizontal alignment.
My desired effect in the editing calc.
oRange.merge()
oCell = oSheet.getCellByPosition(0, 0)
oCell.HoriJustify = 2
oCell.VertJustify = 2
Merged data with vertical and horizontal alignment ,previous data in many cells b1-c1 and a2-c2 and a3-c3 lost.
The real effect.
How to fix my code to get the desired effect?
import uno
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
svcmgr = context.ServiceManager
desktop = svcmgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
oDoc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
oSheet = oDoc.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:C3")
tup = (('a1','a2','a3'),('b1','b2','b3'),('c1','c2','c3'),)
oRange.setDataArray(tup)
target =''
for item in tup:
tmp = ' '.join(item)
target = target + tmp + ' '
target = target.strip()
oRange.merge(True)
oCell = oSheet.getCellByPosition(0, 0)
oCell.String = target
oCell.HoriJustify = 2
oCell.VertJustify = 2
I'm not sure, but I think UNO has no way of knowing that you want to rearrange the data into the merged cell that way. What UNO does is "copy" the data from the "main" cell (the top left one) and "paste" its data into the merged cell. Therefore, what you could do is change the data of the main cell before merging. Check the example below.
# get range
oRange = oSheet.getCellRangeByName("A1:C3")
# build string
flat_list = [str(item) for sublist in oRange.getDataArray() for item in sublist]
string = ' '.join(flat_list)
# put string into main cell
main_cell = oRange.getCellByPosition(0, 0)
main_cell.setString(string)
# merge
oRange.merge()

How to save data in excel file MATLAB?

I want to save pitch,yaw and roll data in excel file for all frames. Eg: if i have 200 frames then i want to save 200 frames information in excel file. I have tried but my code only stores one frame data.exceldata
fitting_model='models/Chehra_f1.0.mat';
load(fitting_model);
mov=VideoReader('7_a.avi'); %Read video file and create an object
c=mov.NumberOfFrames;
for k=1:c
a = read(mov, k);
img=im2double(a);
disp(['Detecting Face in ']);
faceDetector = vision.CascadeObjectDetector(); % detect face in an image
bbox = step(faceDetector, img); %create boundary box around face
test_init_shape = InitShape(bbox,refShape); %initialize facial points in variable
test_init_shape = reshape(test_init_shape,49,2);
if size(img,3) == 3
test_input_image = im2double(rgb2gray(img));
else
test_input_image = im2double((img));
end
disp(['Fitting']);
MaxIter=6;
test_points = Fitting(test_input_image,test_init_shape,RegMat,MaxIter);
load('3D_Shape_Model.mat');
n=49;
test_image=img;
imshow(test_image);hold on;
% % Compute 3D Head Pose
if(n==49)
test_shape=test_points;
[pitch,yaw,roll] = ComputePose(PDM_49,test_shape(:));
filename='framesdata.xlsx';
header = {'Pitch', 'yaw ','roll'};
new_data = num2cell([pitch(:), yaw(:), roll(:)]);
output = [header; new_data];
xlswrite(filename,output);
end
plot(test_shape(:,1),test_shape(:,2),'b*');
title([num2str(i),' : Pitch = ',num2str(pitch),' ; Yaw = ',num2str(yaw),' ; Roll = ',num2str(roll)]);
set(gcf,'units','normalized','outerposition',[0 0 1 1]);
pause(0.5);
close all;
end
As #excaza stated, you will need to move the xlswrite command out of your loop or specify the cells you are writing. Please see the xlswrite Doc for more information. The correct syntax would be :
xlswrite(filename,A,xlRange)
The following is the example they provide:
filename = 'testdata.xlsx';
A = {'Time','Temperature'; 12,98; 13,99; 14,97};
sheet = 2;
xlRange = 'E1';
xlswrite(filename,A,sheet,xlRange)
You will just need to provide xlswrite the address to start writing data.

write excel file to many folders in directory using matlab

I need to write an excel file to many folders ( folder* ) under D:\ and loop over them to further process individually.
i tried the following code for long time ..
srcFolders = dir('D:\folder*');
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
xlswrite('srcFolders\filename.xls', srcFolders(folder).name,'Sheet1', folder_range);
end
I'm assuming that you want to write different sets of data to a Excel file and were just having some trouble. If that's not accurate comment and let me know.
%Just generating some arbitrary data
data = arrayfun(#(m,n) rand(m,n), randi(50, 9, 1), randi(50, 9, 1), 'uni', 0);
%The base file path
path = 'D:';
%The pattern used to choose the folders
folderPattern = 'folder*';
%The files you want to write to
srcFiles = {'A', 'B', 'D'};
%And the extension
ext = '.xlsx';
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
srcFolders = fullfile(path, {srcFolders.name});
%Construct the full file path
fullPath = cellfun(#(f) fullfile(f, strcat(srcFiles(:), ext)), srcFolders, 'uni', 0);
fullPath = vertcat(fullPath{:});
%Write the data to the files
for i = 1:length(fullPath)
xlswrite(fullPath{i}, data{i})
end
Edit:
Based on OP's feed.
Note for the second overhaul. I didn't test this and I'm done. This was way to much for a single question and you are abusing the way this website is supposed to work.
%The base file path
path = 'D:';
%Relative reference to reference images
ImageRefLocations = {'Ref\RefI1.jpg', 'Ref\RefI2.png', 'Ref\RefI3.jpg'};
%Base Image location
baseImage = fullfile(path, ImageRefLocations(:));
%The pattern used to choose the folders
folderPattern = 'folder*';
%The image extension
[~, ~, ext] = unique(cellfun(#(f) fileparts(f), baseImage, 'uni', 0));
%The excel extension
ExcelExt = '.xlsx';
msg = {' = no'; ' = ok'};
i0 = cellfun(#(f) imread(f), baseImage, 'uni', 0);
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
isDir = [srcFolders.isdir];
srcFolders = {srcFolders(isDir).name}';
PathedFolders = fullfile(path, srcFolders);
excelFiles = fullfile(path, strcat(srcFolders, ExcelExt));
for i = 1:length(PathedFolders)
f = PathedFolders{i};
Images = cellfun(#(x) dir(fullfile(f, ['*', x])), ext, 'uni', 0);
Images = vertcat(Images{:});
if isempty(Images)
continue
end
Images = {Images.name}';
[~, ImageNames, ~] = cellfun(#(x) fileparts(x), Images, 'uni', 0);
ImageList = fullfile(f, Images);
match = zeros(size(ImageList));
for j = 1:length(ImageList)
image = imread(ImageList{j});
for k = 1:length(i0)
if ~all(size(image) == size(i0{k}))
continue
end
match(j) = all(image(:) == i0{k}(:));
if match(j)
continue
end
end
end
matchMessage = strcat(Images, msg(match + 1));
xlswrite(excelFiles{i}, matchMessage)
end

Writing to Excel sheet based on image difference using matlab

I have some folders named test* from test 1 to test 100 for example, I need to print names of folders as header in first row.
Then I need to check my test image image2 with each image inside these folders if the diff bigger than 0.05 between my test image2 and every images from each folder test* will write 1 otherwise write 0. till to testn.
My code is as follow :
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg'); % Image 2
x = diff( Image2 , Image1)
% any suggestion here to get my output for printing in excel
if (x >= 0.05)
xlswrite(xlsfile, srcFiles(i), ‘0’, ‘A1’);
else
xlswrite(xlsfile, srcFiles(i), ‘1’, ‘A1’);
end
end
end
thanks
%On every 'folder loop', increment the column range so you have 1 column by folder
%On every 'file loop', increment the row range so you have 1 row by file
xls_filename = 'foo.xls'; %The name of your xls file
xls_sheet = 'sheet_name'; % Put here the name of the sheet you want to write in
column_range = 'A' % Initialisation of the column range
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
folder_range = strcat(column_range, '1');
xlswrite(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';
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg');
x = diff( Image2 , Image1);
file_range = strcat(column_range, row_range);
if (x >= 0.05)
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
row_range = char(row_range + 1); %Moving to the next row
end
column_range = char(column_range + 1); %Moving to the next column
end

Matlab: strange file was created when I color cell in excel

this code has to color the J1 cell by a given rgb.
row_number_excel = 1;
representative_red = 205;
representative_green = 211;
representative_blue = 201;
headers = {'J'};
rgb = [representative_red representative_green representative_blue]; %# if you have 0 to 1 values multiply by 255 and round
clr = rgb * [1 256 256^2]'; %# convert to long number Excel understands
pwd = 'D:\grapes\main';
e = actxserver ('Excel.Application'); % open Activex server
filename = fullfile(pwd,'example.xls'); %# full path required
if exist(filename,'file')
ewb = e.Workbooks.Open(filename); %# open the file
else
error('File does not exist.') %# or create a new file
end
esh = ewb.ActiveSheet;
for c = 1:row_number_excel
str = num2str(row_number_excel);
esh.Range(strcat(headers{1},str)).Interior.Color = clr;
end
ewb.Save
ewb.Close(false)
e.Quit
I tried to run this code, but the cell was colored by a different color than the given rgb. When I ran the code in the second time, a file was created in my directory, named: "2E60F720". its type is 'file'. Then the program ran and ran and wasn't stopped till I stopped 'EXCEL.EXE' by the task manager. After that the matlab wrote me this:
"??? Error: The remote procedure call failed.
Error in ==> test1 at 212 ewb.
Close(false);"
can someone help me please?
I captured the screen. in the left side, the program is still running, in the right side, this is my directory. I marked the file that was created.
thanks!
the solution that solved my question is:
row_number_excel = 1;
representative_red = 205;
representative_green = 211;
representative_blue = 201;
headers = {'J'};
rgb = [representative_red representative_green representative_blue]; %# if you have 0 to 1 values multiply by 255 and round
clr = rgb * [1 256 256^2]'; %# convert to long number Excel understands
pwd = 'D:\grapes\main';
e = actxserver ('Excel.Application'); % open Activex server
filename = fullfile(pwd,'example.xls'); %# full path required
if exist(filename,'file')
ewb = e.Workbooks.Open(filename); %# open the file
else
error('File does not exist.') %# or create a new file
end
esh = ewb.ActiveSheet;
for c = 1:row_number_excel
str = num2str(row_number_excel);
esh.Range(strcat(headers{1},str)).Interior.Color = clr;
end
xlWorkbookDefault = 51; %# it's the Excel constant, not sure how to pass it other way
ewb.SaveAs(fullfile(pwd,'example2'), xlWorkbookDefault)
ewb.Close(false)
e.Quit
thanks to #yuk!
The trouble line is saving the file with ewb.Save.
Your file is actually in the old format (excel 2003), not sure if it's support true RGB colors, it might be the reason.
I'd recommend to save the file with a new name and the latest format. Put this as the last lines:
xlWorkbookDefault = 51; %# it's the Excel constant, not sure how to pass it other way
ewb.SaveAs(fullfile(pwd,'example2'), xlWorkbookDefault)
ewb.Close(false)
e.Quit

Resources