Color image pixel permutation not reversible - image

I performed color image permutation using 2D sine-map for RGB image. The code uses this map to perform pixel location permutation for each RGB channel in the image. Then, I used the same map with the same initial parameters to inverse the permutation. The problem is the code only perform correct inverse permutation for one channel only the other channels is not recovered. See the attached images of the permuted and the recovered image.
%% Image Encryption Demo - Encryption and Decryption
clear all
close all
clc
%% 1. Load plaintext images
% Image 1
I = imread('D:\1\1.jpg');
Ir = I(:,:,1);
Ig = I(:,:,2);
Ib = I(:,:,3);
K=1;
%% 2. Encryption
%[CI,K] = Logistic2D_ImageCipher(I,'encryption');
[CIb,K] = Logistic2D_ImageCipher(Ib,'encryption');
clearvars -except CIb Ir Ig Ib K I;
[CIr,K] = Logistic2D_ImageCipher(Ir,'encryption');
clearvars -except CIb CIr Ir Ig Ib K I;
[CIg,K] = Logistic2D_ImageCipher(Ig,'encryption');
clearvars -except CIb CIr CIg Ir Ig Ib K I;
CI = cat(3,CIr,CIg,CIb);
%% 3. Decryption
%DI = Logistic2D_ImageCipher(CI,'decryption',K);
DIb = Logistic2D_ImageCipher(CIb,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb CI;
DIg = Logistic2D_ImageCipher(CIg,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb DIg CI;
DIr = Logistic2D_ImageCipher(CIr,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb DIg DIr CI;
DI = cat(3,DIr,DIg,DIb);
%% 4. Analaysis
% Histogram
%title('aaa');
figure,subplot(221),imshow(I,[]),subplot(222),imshow(CI,[])
subplot(223),imhist(I),subplot(224),imhist(CI)
title('aaa2');
figure,subplot(221),imshow(DI,[])
function varargout = Logistic2D_ImageCipher(P,para,K)
%% 1. Initialization
% 1.1. Genereate Random Key if K is not given
if ~exist('K','var') && strcmp(para,'encryption')
K = round(rand(1,256));
varOutN = 2;
elseif ~exist('K','var') && strcmp(para,'decryption')
error('Cannot Complete Decryption without Encryption Key')
else
varOutN = 1;
end
% 1.2. Translate K to map formats
transFrac = #(K,st,ed) sum(K(st:ed).*2.^(-(1:(ed-st+1))));
x0 = transFrac(K,1,52);
y0 = transFrac(K,53,104);
a=0.8;
b =0.3;
r = transFrac(K,105,156)*.08+1.11;
T = transFrac(K,157,208);
turb = blkproc(K(209:256),[1,8],#(x) bi2de(x));
MN = numel(P);
Logistic2D = #(x,y,a) [sin(pi*a*(y+3)*x*(1-x)), sin(pi*a*(x+3)*y*(1-y))];
format long eng
%% 2. Estimate cipher rounds
if max(P(:))>1
F = 256;
S = 4;
else
F = 2;
S = 32;
end
P = double(P);
iter = 1;
%iter = ceil(log2(numel(P))/log2(S));
%% 3. Image Cipher
C = double(P);
switch para
case 'encryption'
for i = 1:iter
tx0 = mod(log(turb(mod(i-1,6)+1)+i)*x0+T,1);
ty0 = mod(log(turb(mod(i-1,6)+1)+i)*y0+T,1);
xy = zeros(MN,2);
for n = 1:MN
if n == 1
xy(n,:) = (Logistic2D(tx0,ty0,a));
else
xy(n,:) = (Logistic2D(xy(n-1,1),xy(n-1,2),a));
end
end
R = cat(3,reshape(xy(:,1),size(P,1),size(P,2)),reshape(xy(:,2),size(P,1),size(P,2)));
C = LogisticPermutation(C,R,'encryption');
end
case 'decryption'
for i = iter:-1:1
tx0 = mod(log(turb(mod(i-1,6)+1)+i)*x0+T,1);
ty0 = mod(log(turb(mod(i-1,6)+1)+i)*y0+T,1);
xy = zeros(MN,2);
for n = 1:MN
if n == 1
xy(n,:) = (Logistic2D(tx0,ty0,a));
else
xy(n,:) = (Logistic2D(xy(n-1,1),xy(n-1,2),a));
end
end
R = cat(3,reshape(xy(:,1),size(P,1),size(P,2)),reshape(xy(:,2),size(P,1),size(P,2)));
C = LogisticPermutation(C,R,'decryption');
end
end
%% 4. Output
switch F
case 2
C = logical(C);
case 256
C = uint8(C);
end
switch varOutN
case 1
varargout{1} = C;
case 2
varargout{1} = C;
varargout{2} = K;
end
function C = LogisticPermutation(P,R,para)
C0 = zeros(size(P));
C = C0;
switch para
case 'encryption'
% 1. Shuffling within a Column
[v,Epix] = sort(R(:,:,1),1);
for i = 1:size(R,1)
C0(:,i) = P(Epix(:,i),i);
end
% 2. Shuffling within a Row
[v,Epiy] = sort(R(:,:,2),2);
for j = 1:size(R,2)
C(j,:) = C0(j,Epiy(j,:));
end
case 'decryption'
% 1. Shuffling within a Row
[v,Epiy] = sort(R(:,:,2),2);
for j = 1:size(R,2)
C0(j,Epiy(j,:)) = P(j,:);
end
% 2. Shuffling within a Column
[v,Epix] = sort(R(:,:,1),1);
for i = 1:size(R,1)
C(Epix(:,i),i) = C0(:,i);
end
end

It didn't work because you overwrote K in the encryption stage, and it was different for each channel, so the decryption only worked correctly for the last channel that created K. If you're using the MATLAB editor, you should pay attention to the mlint warnings (square at the top right that should be always be green) - you could say that this is what told me the answer to your problem.
Here's a fixed version of the first part of the script:
function q50823167
%% 1. Load plaintext images
% Image 1
I = imread(fullfile(matlabroot, 'examples', 'wavelet', 'mandrill.jpg'));
Ir = I(:,:,1);
Ig = I(:,:,2);
Ib = I(:,:,3);
%% 2. Encryption
%[CI,K] = Logistic2D_ImageCipher(I,'encryption');
[CIb,Kb] = Logistic2D_ImageCipher(Ib,'encryption');
[CIr,Kr] = Logistic2D_ImageCipher(Ir,'encryption');
[CIg,Kg] = Logistic2D_ImageCipher(Ig,'encryption');
CI = cat(3,CIr,CIg,CIb);
%% 3. Decryption
%DI = Logistic2D_ImageCipher(CI,'decryption',K);
DIb = Logistic2D_ImageCipher(CIb,'decryption',Kb);
DIg = Logistic2D_ImageCipher(CIg,'decryption',Kg);
DIr = Logistic2D_ImageCipher(CIr,'decryption',Kr);
DI = cat(3,DIr,DIg,DIb);
%% 4. Analaysis
% Histogram
%title('aaa');
figure,subplot(221),imshow(I,[]),subplot(222),imshow(CI,[])
subplot(223),imhist(I),subplot(224),imhist(CI)
title('aaa2');
figure,subplot(221),imshow(DI,[])
Note that you don't have to clear variables every time.

Related

Experimenting inverting pictures with Octave

First time using Octave to experiment inverting an image. My filename is LinearAlgebraLab1.m and after I run the file with Octave I get error "error: no such file, '/home/LinearAlgebraLab1.m'"
However, before this, I was getting an error that my .jpg file couldn't be found. What should I change to have Octave run my script correctly without any errors?
%% import image
C = imread('MonaLisa2.jpg');
%% set slopes and intercepts for color transformation
redSlope = 1;
redIntercept = -80;
greenSlope = -.75;
greenIntercept = 150;
blueSlope = -.50;
blueIntercept = 200;
%%redSlope = 1;
%%redIntercept = -80;
%%greenSlope = -.75;
%%greenIntercept = 150;
%%blueSlope = -.50;
%%blueIntercept = 200; redSlope = 1;
%% store RGB channels from image separately
R = C(:,:,1);
G = C(:,:,2);
B = C(:,:,3);
C2 = C;
S=size(C);
m=S(1,1);
n=S(1,2);
%h=S(1,3);
%% change red channel
M = R;
%%M2 = redSlope*cast(M,'double') + redIntercept*ones(786,579);
M2 = redSlope*cast(M,'double') + redIntercept*ones(m,n);
C2(:,:,1) = M2;
%% change green channel
M = G;
M2 = greenSlope*cast(M,'double') + greenIntercept*ones(m,n);
C2(:,:,2) = M2;
%% change blue channel
M = B;
M2 = blueSlope*cast(M,'double') + blueIntercept*ones(m,n);
C2(:,:,3) = M2;
%% visualize new image
image(C2)
axis equal tight off
set(gca,'position',[0 0 1 1],'units','normalized')

Matalb code Error in Selecting Disc view of Waves

I am getting an error when I run this code for disc waves. The code is attached.
The Error is in line 137 and 292. Please help in resolving issue.
function waves
% WAVES Wave equation in one and two space dimensions.
% The two-dimensional domains include a pi-by-pi square, a unit disc,
% a three-quarter circular sector and the L-shaped union of three squares.
% The eigenfunctions of the square are sin(m*x)*sin(n*y). With polar
% coordinates, the eigenfunctions of the disc and the sector involve Bessel
% functions. The eigenfunctions of the L-shaped domain also involve
% Bessel functions and are computed by the MATLAB function membranetx.m.
% 2-D eigenvalues and eigenfunctions
m = 11; % Determines number of grid points
speed = 1;
bvals = [1; 0; 0; 0; 0];
t = 0;
while bvals(5) == 0
% Initialize figure
shg
clf reset
set(gcf,'doublebuffer','on','menubar','none','tag','', ...
'numbertitle','off','name','Waves','colormap',hot(64));
for k= 1:5
b(k) = uicontrol('style','toggle','value',bvals(k), ...
'units','normal','position',[.15*k .01 .14 .05]);
end
set(b(1),'style','pop','string', ...
{'1-d','square','disc','sector'})
set(b(2),'string','modes/wave')
set(b(3),'string','slower')
set(b(4),'string','faster')
set(b(5),'string','close')
if bvals(3)==1
speed = speed/sqrt(2);
set(b(3),'value',0);
end
if bvals(4)==1
speed = speed*sqrt(2);
set(b(4),'value',0);
end
bvals = cell2mat(get(b,'value'));
region = bvals(1);
modes = bvals(2)==0;
if region == 1
% 1-D
x = (0:4*m)/(4*m)*pi;
orange = [1 1/3 0];
gray = get(gcf,'color');
if modes
% 1-D modes
for k = 1:4
subplot(2,2,k)
h(k) = plot(x,zeros(size(x)));
axis([0 pi -3/2 3/2])
set(h(k),'color',orange,'linewidth',3)
set(gca,'color',gray','xtick',[],'ytick',[])
end
delta = 0.005*speed;
bvs = bvals;
while all(bvs == bvals)
t = t + delta;
for k = 1:4
u = sin(k*t)*sin(k*x);
set(h(k),'ydata',u)
end
drawnow
bvs = cell2mat(get(b,'value'));
end
else
% 1-D wave
h = plot(x,zeros(size(x)));
axis([0 pi -9/4 9/4])
set(h,'color',orange,'linewidth',3)
set(gca,'color',gray','xtick',[],'ytick',[])
delta = 0.005*speed;
a = 1./(1:4);
bvs = bvals;
while all(bvs == bvals)
t = t + delta;
u = zeros(size(x));
for k = 1:4
u = u + a(k)*sin(k*t)*sin(k*x);
end
set(h,'ydata',u)
drawnow
bvs = cell2mat(get(b,'value'));
end
end
elseif region <= 5
switch region
case 2
% Square
x = (0:2*m)/(2*m)*pi;
y = x';
lambda = zeros(4,1);
V = cell(4,1);
k = 0;
for i = 1:2
for j = 1:2
k = k+1;
lambda(k) = i^2 + j^2;
V{k} = sin(i*y)*sin(j*x);
end
end
ax = [0 pi 0 pi -1.75 1.75];
case 3
% Disc, mu = zeros of J_0(r) and J_1(r)
mu = [bjzeros(0,2) bjzeros(1,2)];
[r,theta] = meshgrid((0:m)/m,(-m:m)/m*pi);
x = r.*cos(theta);
y = r.*sin(theta);
V = cell(4,1);
k = 0;
for j = 0:1
for i = 1:2
k = k+1;
if j == 0
V{k} = besselj(0,mu(k)*r);
else
V{k} = besselj(j,mu(k)*r).*sin(j*theta);
end
V{k} = V{k}/max(max(abs(V{k})));
end
end
lambda = mu.^2;
ax = [-1 1 -1 1 -1.75 1.75];
case 4
% Circular sector , mu = zeros of J_(2/3)(r) and J_(4/3)(r)
mu = [bjzeros(2/3,2) bjzeros(4/3,2)];
[r,theta] = meshgrid((0:m)/m,(3/4)*(0:2*m)/m*pi);
x = r.*cos(theta+pi);
y = r.*sin(theta+pi);
V = cell(4,1);
k = 0;
for j = 1:2
for i = 1:2
k = k+1;
alpha = 2*j/3;
V{k} = besselj(alpha,mu(k)*r).*sin(alpha*theta);
V{k} = V{k}/max(max(abs(V{k})));
end
end
lambda = mu.^2;
ax = [-1 1 -1 1 -1.75 1.75];
case 5\
% L-membrane
x = (-m:m)/m;
y = x';
lambda = zeros(4,1);
V = cell(4,1);
for k = 1:4
[L lambda(k)] = membranetx(k,m,9,9);
L(m+2:2*m+1,m+2:2*m+1) = NaN;
V{k} = rot90(L,-1);
end
ax = [-1 1 -1 1 -1.75 1.75];
end
if modes
% 2-D modes
p = [.02 .52 .02 .52];
q = [.52 .52 .02 .02];
for k = 1:4
axes('position',[p(k) q(k) .46 .46]);
h(k) = surf(x,y,zeros(size(V{k})));
axis(ax)
axis off
view(225,30);
caxis([-1.5 1]);
end
delta = .08*speed;
mu = sqrt(lambda(:));
bvs = bvals;
while all(bvs == bvals)
t = t + delta;
for k = 1:4
U = 1.5*sin(mu(k)*t)*V{k};
set(h(k),'zdata',U)
set(h(k),'cdata',U)
end
drawnow
bvs = cell2mat(get(b,'value'));
end
else
% 2-D wave
h = surf(x,y,zeros(size(V{1})));
axis(ax);
axis off
view(225,30);
caxis([-1.5 1]);
delta = .02*speed;
mu = sqrt(lambda(:));
a = 1.25./(1:4);
bvs = bvals;
while all(bvs == bvals)
t = t + delta;
U = zeros(size(V{1}));
for k = 1:4
U = U + a(k)*sin(mu(k)*t)*V{k};
end
set(h,'zdata',U)
set(h,'cdata',U)
drawnow
bvs = cell2mat(get(b,'value'));
end
end
elseif region == 6
figure
bizcard
set(b(1),'value',1)
end
% Retain uicontrol values
bvals = cell2mat(get(b,'value'));
end
close
% -------------------------------
function z = bjzeros(n,k)
% BJZEROS Zeros of the Bessel function.
% z = bjzeros(n,k) is the first k zeros of besselj(n,x)
% delta must be chosen so that the linear search can take
% steps as large as possible without skipping any zeros.
% delta is approx bjzero(0,2)-bjzero(0,1)
delta = .99*pi;
Jsubn = inline('besselj(n,x)''x','n');
a = n+1;
fa = besselj(n,a);
z = zeros(1,k);
j = 0;
while j < k
b = a + delta;
fb = besselj(n,b);
if sign(fb) ~= sign(fa)
j = j+1;
z(j) = fzerotx(Jsubn,[a b],n);
end
a = b;
fa = fb;
end

How to avoid overlapping between title and labels in Matlab's pie chart?

I'm using the next code to plot in a pie chart the percentage of values in a matrix that are greater/smaller than 1. The thing is that when I want to put the title above the graph, it overlaps with the label of one of the groups.
I tried replacing it with text() but it didn't worked, and Documentation on pie say nothing to this. How can I avoid this overlap?
eigen = []; % Modes array
c2 = 170; % Sound speed divided by 2
%% Room dimensions
lx = 5.74;
ly = 8.1;
lz = 4.66;
i = 1; % Index for modes array
for nz = 0:50
for ny = 0:50
for nx = 0:50
aux = c2 * sqrt((nx/lx)^2+(ny/ly)^2+(nz/lz)^2);
if aux < 400 %% If value is into our range of interest
eigen(i) = aux;
i=i+1;
end
end
end
end
eigen = round(sort(eigen'),1);
eigen
% dif = eigen(2:end)-eigen(1:end-1); % Distance between modes
x = 0; %% dif >= 1
y = 0; %% dif <= 1
dif = [];
for i=2:length(eigen)
if eigen(i)-eigen(i-1) >= 1
x = x+1;
else
y = y+1;
end
end
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
title('Distance between modes')
You can rotate the pie chart so that the figure look better. Further, you can use position to allocate your text as follows,
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
view([90 90]) % this is to rotate the chart
textPositions_cell = get(hText,{'Position'});
textPositions = cell2mat(textPositions_cell);
textPositions(:,1) = textPositions(:,1) + 0.2; % replace 0.2 with any offset value you want
hText(1).Position = textPositions(1,:);
hText(2).Position = textPositions(2,:);
title('Distance between modes')
You can change only the text position (without rotation) by deleting view command.

Inverse image rotation

I have written the following code without any Matlab built-in functions to rotate an image. I tried to write another loop to invert the rotation. the image does rotate back but I still get the size of the previously rotated image. How can I get rid of the black parts in the image?
INPUT_IMAGE = 'forest.png';
img_in=double(imread(INPUT_IMAGE))./255;
h=size(img_in,1);
w=size(img_in,2);
R=[cos(th) -sin(th) 0 ; sin(th) cos(th) 0 ; 0 0 1];
T=[1 0 (-w/2) ; 0 1 (-h/2) ; 0 0 1];
F=inv(T)*R*T;
img_out=zeros(h,w,3);
%Rotate image
for i=1:w
for j=1:h
a = [i ; j ; 1];
b = inv(F) * a;
x = b(1)/b(3);
y = b(2)/b(3);
x = floor(x);
y = floor(y);
if (x>0 & x<=W & j>0 & j<=H)
img_out(y,x,:)=img_in(j,i,:);
end
end
end
img_out2=zeros(h,w,3);
%invert rotation
for i=1:w
for j=1:h
a = [i ; j ; 1];
b = F * a;
x = b(1)/b(3);
y = b(2)/b(3);
x = floor(x);
y = floor(y);
if (x>0 & x<=W & j>0 & j<=H)
img_out2(y,x,:)=img_out(j,i,:);
end
end
end
The result:
I know the image has black gaps due to the forward mapping but I'm not concerned about that as I'm trying to implement a code without built-in functions that would only rotate the image back so I can calculate the error.
Instead of iterating the source image, inverse transformation matrix, and iterate destination image.
Iterating destination image guarantees to have no holes (each pixel gets a value).
The code you have posted is not working, please fix it...
I based my answer on your previous post: Matlab image rotation
I used 'peppers.png' instead of 'forest.png' (I can't find 'forest.png', next time, please add the image to your post).
The example code do the following:
Rotate input image (You may treat it as "reverse transformation").
Rotate result image back (using inverse transformation matrix).
Display absolute difference of original image and result image.
close all;
clear all;
img_in = 'peppers.png';
img_in =double(imread(img_in))./255;
orig_in = img_in;
h=size(img_in,1);
w=size(img_in,2);
th = pi/4;
R=[cos(th) -sin(th) 0 ; sin(th) cos(th) 0 ; 0 0 1];
T=[1 0 (-w/2) ; 0 1 (-h/2) ; 0 0 1];
F=inv(T)*R*T;
img_out=zeros(h,w,3);
%Rotate image
for i=1:w
for j=1:h
x = [i ; j ; 1];
y = F * x;
a = y(1)/y(3);
b = y(2)/y(3);
a = round(a);
b = round(b);
if (a>0 && a<=w && b>0 && b<=h)
img_out(j,i,:)=img_in(b,a,:);
end
end
end
figure;imshow(img_out);
%Rotate back
%---------------------------------------------------------
img_in = img_out;
img_out = zeros(h,w,3);
%Inverse transformation matrix.
F = inv(F);
%Rotate image (back)
for i=1:w
for j=1:h
x = [i ; j ; 1];
y = F * x;
a = y(1)/y(3);
b = y(2)/y(3);
a = round(a);
b = round(b);
if (a>0 && a<=w && b>0 && b<=h)
img_out(j,i,:)=img_in(b,a,:);
end
end
end
figure;imshow(img_out);
img_diff = abs(orig_in - img_out);
figure;imshow(img_diff);
img_diff image:

I want to correct this code for images, what change need to do..?

Currently i am recognzing a face, means i have to find a face which we have to test is in training database or not..! So, i have to decide yes or no..
Yes means find image, and no means print message that NO IMAGE IN DATABASE. I have a program, Currently this program is finding a correct image correctly, but even when there is no image, even it shows other image which not matches.. Actually it should print NO IMAGE IN DATABASE.
So, How to do..?
Here is a Test and training images data on this link.
http://www.fileconvoy.com/dfl.php?id=g6e59fe8105a6e6389994740914b7b2fc99eb3e445
My Program is in terms of different four .m files, and it is here,we have to run only first code.. and remaining 3 are functions, it is also given here..**
clear all
clc
close all
TrainDatabasePath = uigetdir('D:\Program Files\MATLAB\R2006a\work', 'Select training database path' );
TestDatabasePath = uigetdir('D:\Program Files\MATLAB\R2006a\work', 'Select test database path');
prompt = {'Enter test image name (a number between 1 to 10):'};
dlg_title = 'Input of PCA-Based Face Recognition System';
num_lines= 1;
def = {'1'};
TestImage = inputdlg(prompt,dlg_title,num_lines,def);
TestImage = strcat(TestDatabasePath,'\',char(TestImage),'.jpg');
im = imread(TestImage);
T = CreateDatabase(TrainDatabasePath);
[m, A, Eigenfaces] = EigenfaceCore(T);
OutputName = Recognition(TestImage, m, A, Eigenfaces);
SelectedImage = strcat(TrainDatabasePath,'\',OutputName);
SelectedImage = imread(SelectedImage);
imshow(im)
title('Test Image');
figure,imshow(SelectedImage);
title('Equivalent Image');
str = strcat('Matched image is : ',OutputName);
disp(str)
function T = CreateDatabase(TrainDatabasePath)
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,'Thu mbs.db'))
Train_Number = Train_Number + 1; % Number of all images in the training database
end
end
T = [];
for i = 1 : Train_Number
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)
m = mean(T,2); % Computing the average face image m = (1/P)*sum(Tj's) (j = 1 : P)
Train_Number = size(T,2);
A = [];
for i = 1 : Train_Number
temp = double(T(:,i)) - m;
Ai = Ti - m
A = [A temp]; % Merging all centered images
end
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'.
L_eig_vec = [];
for i = 1 : size(V,2)
if( D(i,i)>1 )
L_eig_vec = [L_eig_vec V(:,i)];
end
end
Eigenfaces = A * L_eig_vec; % A: centered image vectors
function OutputName = Recognition(TestImage, m, A, Eigenfaces)
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
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
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');
So, how to generate error massege when no image matches..?
At the moment, your application appears to find the most similar image (you appear to be using Euclidean distance as you measure of similarity), and return it. There doesn't seem to be any concept of whether the image "matches" or not.
Define a threshold on similarity, and then determine whether your most similar image meets that threshold. If it does, return it, otherwise display an error message.

Resources