-2

I have a MATLAB code that does facial recognition on an image by first converting the image into a gray image and assigning image to a 1D array I need to convert this code into C#.

This Function reads the images:

function T = CreateDatabase(TrainDatabasePath)

%%%%%%%%%%%%%%%%%%%%%%%% File management
TrainFiles = dir(TrainDatabasePath);
Train_Number = 0;

for i = 1:size(TrainFiles,1)
    if not(strcmp(TrainFiles(i).name,'.')|strcmp(TrainFiles(i).name,'..')|strcmp(TrainFiles(i).name,'Thumbs.db'))
        Train_Number = Train_Number + 1; % Number of all images in the training database
    end
end

%%%%%%%%%%%%%%%%%%%%%%%% Construction of 2D matrix from 1D image vectors
T = [];
for i = 1 : Train_Number
    
    % I have chosen the name of each image in databases as a corresponding
    % number. However, it is not mandatory!
    str = int2str(i);
    str = strcat('\',str,'.jpg');
    str = strcat(TrainDatabasePath,str);
    
    img = imread(str);
    img = rgb2gray(img);
    
    [irow icol] = size(img);
   
    temp = reshape(img',irow*icol,1);   % Reshaping 2D images into 1D image vectors
    T = [T temp]; % 'T' grows after each turn                    
end

Getting Eigen values

function [m, A, Eigenfaces] = EigenfaceCore(T)
                
 
%%%%%%%%%%%%%%%%%%%%%%%% Calculating the mean image 
m = mean(T,2); % Computing the average face image m = (1/P)*sum(Tj's)    (j = 1 : P)
Train_Number = size(T,2);

%%%%%%%%%%%%%%%%%%%%%%%% Calculating the deviation of each image from mean image
A = [];  
for i = 1 : Train_Number
    temp = double(T(:,i)) - m; % Computing the difference image for each image in the training set Ai = Ti - m
    A = [A temp]; % Merging all centered images
end

%%%%%%%%%%%%%%%%%%%%%%%% Snapshot method of Eigenface methos
% We know from linear algebra theory that for a PxQ matrix, the maximum
% number of non-zero eigenvalues that the matrix can have is min(P-1,Q-1).
% Since the number of training images (P) is usually less than the number
% of pixels (M*N), the most non-zero eigenvalues that can be found are equal
% to P-1. So we can calculate eigenvalues of A'*A (a PxP matrix) instead of
% A*A' (a M*NxM*N matrix). It is clear that the dimensions of A*A' is much
% larger that A'*A. So the dimensionality will decrease.

L = A'*A; % L is the surrogate of covariance matrix C=A*A'.
[V D] = eig(L); % Diagonal elements of D are the eigenvalues for both L=A'*A and C=A*A'.

%%%%%%%%%%%%%%%%%%%%%%%% Sorting and eliminating eigenvalues
% All eigenvalues of matrix L are sorted and those who are less than a
% specified threshold, are eliminated. So the number of non-zero
% eigenvectors may be less than (P-1).

L_eig_vec = [];
for i = 1 : size(V,2) 
    if( D(i,i)>1 )
        L_eig_vec = [L_eig_vec V(:,i)];
    end
end

%%%%%%%%%%%%%%%%%%%%%%%% Calculating the eigenvectors of covariance matrix 'C'
% Eigenvectors of covariance matrix C (or so-called "Eigenfaces")
% can be recovered from L's eiegnvectors.
Eigenfaces = A * L_eig_vec; % A: centered image vectors

Recognition

function OutputName = Recognition(TestImage, m, A, Eigenfaces)


               

%%%%%%%%%%%%%%%%%%%%%%%% Projecting centered image vectors into facespace
% All centered images are projected into facespace by multiplying in
% Eigenface basis's. Projected vector of each face will be its corresponding
% feature vector.

ProjectedImages = [];
Train_Number = size(Eigenfaces,2);
for i = 1 : Train_Number
    temp = Eigenfaces'*A(:,i); % Projection of centered images into facespace
    ProjectedImages = [ProjectedImages temp]; 
end

%%%%%%%%%%%%%%%%%%%%%%%% Extracting the PCA features from test image
InputImage = imread(TestImage);
temp = InputImage(:,:,1);

[irow icol] = size(temp);
InImage = reshape(temp',irow*icol,1);
Difference = double(InImage)-m; % Centered test image
ProjectedTestImage = Eigenfaces'*Difference; % Test image feature vector

%%%%%%%%%%%%%%%%%%%%%%%% Calculating Euclidean distances 
Euc_dist = [];
for i = 1 : Train_Number
   q = ProjectedImages(:,i);
    temp = ( norm( ProjectedTestImage - q ) )^2;
    Euc_dist = [Euc_dist temp];
end
[Euc_dist_min , Recognized_index] = min(Euc_dist);
OutputName = strcat(int2str(Recognized_index),'.jpg');


%%%%%%%%%%%%%%%%%%%%%%%% Calculating Mahanalobis %distances 
%maha_dist = [];
%X = []; 
%Y = [];
%for i = 1 : Train_Number
  % S = cov(X);
 %  mu = mean(X);
%temp = (Y(i,:)-mu)*inv(S)*(Y(i,:)-mu)';

%maha_dist = [maha_dist temp];
%end

%[maha_dist_min , Recognized_index] = min(maha_dist);
%OutputName = strcat(int2str(Recognized_index),'.jpg');
Yahya Ahmed
  • 49
  • 2
  • 5

2 Answers2

3

You can call a matlab function from C# client.

Create a MATLAB function, myfunc, in the folder c:\temp\example.

function [x,y] = myfunc(a,b,c) 
x = a + b; 
y = sprintf('Hello %s',c);

In Microsoft® Visual Studio®, add a reference to your C# project to the MATLAB COM object. From the Project menu, select Add Reference.

Select the COM tab in the Add Reference dialog box.

Select the MATLAB application.

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            // Create the MATLAB instance 
            MLApp.MLApp matlab = new MLApp.MLApp(); 

            // Change to the directory where the function is located 
            matlab.Execute(@"cd c:\temp\example"); 

            // Define the output 
            object result = null; 

            // Call the MATLAB function myfunc
            matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world"); 

            // Display result 
            object[] res = result as object[]; 

            Console.WriteLine(res[0]); 
            Console.WriteLine(res[1]); 
            Console.ReadLine(); 
        } 
    } 
} 
flofreelance
  • 944
  • 3
  • 14
  • 31
1

@ptfilo's answer is helpful, but before you do what he suggests you need to convert your *.m files into a DLL that your C# application can add a reference to. First open Matlab and then type libraryCompiler into the command Windows:

enter image description here

enter image description here

Then provide details and click on the green "Package" checkbox:

enter image description here

Please note that this creates a DLL that can be invoked from C# which has fewer limitations than converting the matlab code directly to C# (see https://www.mathworks.com/matlabcentral/answers/21708-s-o-s-matlab-code-convert-to-the-c)

There are more details here:

https://www.mathworks.com/help/compiler_sdk/gs/create-a-dotnet-application-with-matlab-code.html

https://www.mathworks.com/products/matlab-compiler-sdk.html

user8128167
  • 6,929
  • 6
  • 66
  • 79