如何将MATLAB代码转换为C#

时间:2017-03-21 13:27:58

标签: c# matlab image-processing converter image-recognition

我有一个MATLAB代码,通过首先将图像转换为灰色图像并将图像分配给一维数组,对图像进行面部识别 我需要将此代码转换为C#。

此函数读取图像:

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

获得特征值

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

认可

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');

2 个答案:

答案 0 :(得分:3)

你可以call a matlab function from C# client.

  

在文件夹c:\ temp \ example。

中创建一个MATLAB函数myfunc
function [x,y] = myfunc(a,b,c) 
x = a + b; 
y = sprintf('Hello %s',c);
  

在Microsoft®VisualStudio®中,添加对C#项目的引用   MATLAB COM对象。从“项目”菜单中,选择“添加引用”。

     

在“添加引用”对话框中选择“COM”选项卡。

     

选择MATLAB应用程序。

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(); 
        } 
    } 
} 

答案 1 :(得分:0)

@ptfilo的答案很有帮助,但是在执行他建议的操作之前,您需要将* .m文件转换为C#应用程序可以添加引用的DLL。首先打开Matlab,然后在Windows命令中输入libraryCompiler

enter image description here

这里有更多详细信息:

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