本文学习资源来自《机器学习实践指南》
目的
通过某人的一张照片,在他与别人的合影中找到他。
算法描述
- 读取两张图像,生成图像矩阵
- 以两个图像矩阵为基础,调用OpenCV的相关函数完成人脸定位
- 读取两张图像的人脸区域,生成人脸图像矩阵,并将人脸矩阵转换为灰度图
- 比较分析人脸图像矩阵,找到最相近的人脸。
欧氏距离算法
在进行人脸识别是,可使用标准欧氏距离算法。算法基本原理是:
将标准欧氏距离算法作为比较分析人脸图像矩阵方法。
首先,将两个人脸调整为指定大小;
接着,用所包含像素的三元色数值组成特征组,然后将特征组映射为高维空间的某个点(在此称之为特征点);
最后,计算两个人脸图像的特征点映射到高维空间后的距离,以欧氏距离最小者为最匹配的人脸。
下面代码需要OPENCV的data库
https://github.com/opencv/opencv
示例代码
#-*- coding: utf-8 -*-
#code:
#11-2.py
#标准欧氏距离实现的人脸识别
import cv2
import numpy as np
print('loding...')
OPCV_PATH=r"D:/Documents/face"
def get_EuclideanDistance(x,y):
myx=np.array(x)
myy=np.array(y)
return np.sqrt(np.sum((myx-myy)*(myx-myy)))*np.var(myx-myy)
def get_distance(img,findimg):
newsize=(img.shape[1],img.shape[0])
fimg=cv2.resize(findimg,newsize)
my_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# my_fimg=cv2.cvtColor(fimg,cv2.COLORBGR2GRAY)
my_fimg = cv2.cvtColor(fimg, cv2.COLOR_BGR2GRAY)
return get_EuclideanDistance(my_img,my_fimg)
color = (0, 0, 0) # 设置人脸框的颜色
def findface(src, index):
image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
cv2.equalizeHist(image, image) # 灰度图像进行直方图等距化
# 加载OpenCv的面部特征库
classfier = cv2.CascadeClassifier(OPCV_PATH + "/haarcascade_frontalface_alt.xml")
# 找到人脸的位置
# 设定最小图像的大小
divisor = 8
h = image.shape[1]
w = image.shape[0]
minSize = (int(w / divisor), int(h / divisor)) # 这里加了一个取整函数
rect = classfier.detectMultiScale(image, 1.2, 2, cv2.CASCADE_SCALE_IMAGE, minSize)
# if len(rect) > 0: # 如果人脸数组长度大于0
# for faceRect in rect: # 对每一个人脸画矩形框
# x, y, w, h = faceRect
# cv2.rectangle(image, (x, y), (x + w, y + h), color)
# cv2.imshow('img'+str(index),image)
result = []
for r in rect:
result.append([(r[0],r[1]),(r[0]+r[2],r[1]+r[3])])
print(result)
return result
fn = 'billall2.jpg'
fnt = 'billtest.jpg'
my_img=cv2.imread(fn)
face_test=cv2.imread(fnt)
#获取人脸在图像中的坐标
faceresult = findface(my_img,1)
facet_result=findface(face_test,2)
#
myimg = cv2.imread(fn)
myimgt=cv2.imread(fnt)
# #IT 比尔盖茨
isface1 = get_distance(myimg[faceresult[0][0][0]:faceresult[0][1][0],faceresult[0][0][1]:faceresult[0][1][1],:],myimgt[facet_result[0][0][0]:facet_result[0][1][0],facet_result[0][0][1]:facet_result[0][1][1],:])
isface2 = get_distance(myimg[faceresult[1][0][0]:faceresult[1][1][0],faceresult[1][0][1]:faceresult[1][1][1],:],myimgt[facet_result[0][0][0]:facet_result[0][1][0],facet_result[0][0][1]:facet_result[0][1][1],:])
if isface1<isface2:
cv2.rectangle(myimg,faceresult[0][0],faceresult[0][1],(255,0,255))
cv2.rectangle(myimgt,facet_result[0][0],facet_result[0][1],(255,0,255))
else:
cv2.rectangle(myimg,faceresult[1][0],faceresult[1][1],(255,0,255))
cv2.rectangle(myimgt,facet_result[0][0],facet_result[0][1],(255,0,255))
cv2.namedWindow('img')
cv2.imshow('img',myimg)
cv2.namedWindow('imgt')
cv2.imshow('imgt',myimgt)
cv2.waitKey()
cv2.destroyAllWindows()
运行结果:
[外链图片转存中…(img-CE8DvPQJ-1574725941925)]
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容