我必须为uni实现。最近的人脸识别邻居算法,我在matlab中有代码,但是我想在python中实现它。在此代码的matlab中,我得到了大约90%的识别率。在python中,只有1.25%的成功是灾难性的。我为python尝试了不同的方法,但没有成功。您看到错误可能在哪里吗?
Python
import cv2
import numpy as np
from numpy import linalg as LA
from PIL import Image
import math
def load_images(tests):
images = []
for x in range(1,40):
for y in range(1, tests):
temp_im = np.array(cv2.imread(f"s{x}/{y}.pgm", 0))
temp_im = temp_im.reshape((10304, 1))
images.append(temp_im)
return np.array(images)
def algoritm_nn(to_be_found, show_image):
images = load_images(6)
to_be_found = to_be_found.reshape((10304, 1))
min_values = []
for img in images:
rez = LA.norm(np.subtract(to_be_found, img))
min_values.append(rez)
minim = min(min_values)
index = min_values.index(minim)
if(show_image):
img = images[index].reshape((112,92))
img = Image.fromarray(img)
img.show()
img = to_be_found.reshape((112,92))
img = Image.fromarray(img)
img.show()
else:
return index
def statistics(tests):
counter = 0
for x in range(1,40):
for y in range(tests+1, 10):
temp_im = np.array(cv2.imread(f"s{x}/{y}.pgm", 0))
temp_im = temp_im.reshape((10304, 1))
index = algoritm_nn(temp_im,0)
if math.floor(index / tests) + 1 == x:
counter += 1
return (counter/((10-tests)*40)) * 100
print(statistics(6))
Matlab
function index=NN(A,image,norm);
totalimages = size(A,2);
z = zeros(1,totalimages); % vector of distances .
find=zeros(size(image,1)*size(image,2),1); %vector of 10304
find(:,1)=reshape(image,size(image,1)*size(image,2),1);
for i=1:totalimages
switch norm
case 'n1',z(i)=norm(find-A(:,i),1);
case 'n2',z(i)=norm(find-A(:,i),2);
case 'n3',z(i)=norm(find-A(:,i),inf);
case 'n4',z(i)=1-dot(find,A(:,i))/norm(find)*norm(A(:,i));
end
end
[distance,index]=min(z)
对于matlab,我想指定A代表训练矩阵。