部分代码由朋友提供,如有侵权,请及时联系。
1、裁剪图像。
可以自己写,但有时候会出现漏检测。其次,也可以网上下载,但是需要写脚本处理图像的格式以及进行再分类。
网上下载地址:http://conradsanderson.id.au/lfwcrop/

2、读取pairs文件,生成自己的label文件,每行包含图像位置信息以及标签(0-不同人,1-同一个人)
读取

    def read_pairs(self, pairs_filename):pairs = []f = open(pairs_filename, 'r')while True:line = f.readline().strip('\n').split()if not line:breakif len(line) ==3 or len(line) == 4:pairs.append(line) #print(pairs)return pairs

生成

    def get_paths(self, ori_path, pairs):ori_path = 'E:/sign_system/lfw/'file = open('E:/sign_system/execute_system/testcode/labelcrop_3.txt', 'w')labellines = []for i in range(0, len(pairs)):if len(pairs[i]) == 3:labelline = ori_path+pairs[i][0] + '/' + pairs[i][0] + '_' + \'%04d' % int(pairs[i][1]) + '.jpg' + '\t' +ori_path + '/' + \pairs[i][0] + '/' + pairs[i][0] + '_' +'%04d' % int(pairs[i][2])\+ '.jpg' + '\t' + '1\n'labellines.append(labelline)elif len(pairs[i]) == 4:labelline = ori_path+pairs[i][0] + '/' + pairs[i][0] + '_' + \'%04d' % int(pairs[i][1]) + '.jpg' + '\t' + ori_path + '/' +\pairs[i][2] + '/'+ pairs[i][2] + '_' + '%04d' % int(pairs[i][3])\+ '.jpg' + '\t' + '0\n'labellines.append(labelline)else:print("error!!!!")file.writelines(labellines)file.close()

3、再次读取文件,生成label文件中同一行的左右图像特征
读取label文件

    def readImagelist(self,labelFile):file = open(labelFile)lines = file.readlines()file.close()left = []right = []labels = []for line in lines:path = line.strip('\n').split('\t')#read left imageleft.append(path[0])#read right imageright.append(path[1])#read labellabels.append(int(path[2]))assert(len(left) == len(right))assert(len(right) == len(labels))return left, right, labels

提取特征

提取前需要在前面导入模型

        self.model = Model_half()path = '‘’(你需要导入模型的地址)self.model = load_model(path)

提取

    def extractFeature(self, leftImageList, rightImageList):leftfeature = []rightfeature = []   for i in range(0, len(leftImageList)):if (i%200 == 0):print("there are %d images done!"%i)#读取左边图像,并提取特征imagel = cv2.imread(leftImageList[i])#图像标准化,为了提取特征if K.image_data_format() == 'channels_first' and imagel.shape != (1, 3, 224, 224):imagel = resize_image(imagel)                            imagel = imagel.reshape((1, 224, 224, 3))            elif K.image_data_format() == 'channels_last' and imagel.shape != (1, 224, 224, 3):imagel = resize_image(imagel)imagel = imagel.reshape((1, 224, 224, 3))            imagel = imagel.astype('float32')imagel /= 255.0f1 = self.model.predict(imagel, batch_size = 128)[0]leftfeature.append(f1)#读取右边图像,并提取特征imager = cv2.imread(rightImageList[i])     if K.image_data_format() == 'channels_first' and imager.shape != (1, 3, 224, 224):imager = resize_image(imager)                            imager = imager.reshape((1, 224, 224, 3))            elif K.image_data_format() == 'channels_last' and imager.shape != (1, 224, 224, 3):imager = resize_image(imager)imager = imager.reshape((1, 224, 224, 3))            imager = imager.astype('float32')imager /= 255.0 f2 =self.model.predict(imager, batch_size = 128)[0]rightfeature.append(f2)return leftfeature, rightfeature

4、计算余弦相似度并做归一化
注意:余弦相似度与余弦距离的区别,可以参考我的文章:https://blog.csdn.net/u010847579/article/details/88893107
求出余弦相似度

    dis = 1-pw.pairwise_distances(leftfeature, rightfeature, metric='cosine')distance = np.empty((len(labels),))for i in range(len(labels)):distance[i] = dis[i][i]

余弦相似度归一化(这一步也可以不做,看自己的需求)

    distance_norm = np.empty((len(labels)))for i in range(len(labels)):distance_norm[i] = (distance[i]-np.min(distance))/(np.max(distance)-np.min(distance))

5、计算不同阈值下的精确度,确定最佳精度以及生成tpr,fpr的关系图
计算精确度

    def calculate_accuracy(self,distance, labels, num):accuracy = {}predict = np.empty((num,))threshold = 0.1while threshold <= 0.9:for i in range(num):if distance[i] >= threshold:predict[i] = 1else:predict[i] = 0predict_right =0.0for i in range(num):if predict[i] == labels[i]:predict_right += 1.0current_accuracy = (predict_right / num)accuracy[str(threshold)] = current_accuracythreshold = threshold + 0.001#将字典按照value排序temp = sorted(accuracy.items(), key = lambda d:d[1], reverse = True)highestAccuracy = temp[0][1]thres = temp[0][0]return highestAccuracy, thres

生成

fpr, tpr, thresholds = sklearn.metrics.roc_curve(labels, distance_norm)

绘制roc

    def draw_roc_curve(self, fpr,tpr,title='cosine',save_name='roc_lfw'):plt.figure()plt.plot(fpr, tpr)plt.plot([0, 1], [0, 1], 'k--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.0])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic using: '+title)plt.legend(loc="lower right")pathplt = ''(保存的地址)    plt.savefig(pathplt)plt.show()

效果,随便拿的一个轻量化模型。


如图,可以看到最高准确率以及对应的阈值。

以上差不多就整体完成了,如有疑问,可以私信留言。

keras实现LFW测试相关推荐

  1. Keras安装与测试

    Keras是高度封装的包,适合初学者学习深度学习网络框架,比如我这个小白,一切都在尝试中,每天都在安装各种库各种API!!! Keras 安装: 环境 anconda(含pip,python3.6) ...

  2. python keras模块安装检测_Keras安装与测试遇到的坑

    Keras是基于python的深度学习库 Keras是一个高层神经网络API,Keras由纯Python编写而成并基Tensorflow.Theano以及CNTK后端. 安装步骤及遇到的坑: (1)安 ...

  3. Ubuntu 18.04+NVidia显卡+Anaconda3+Tensorflow-GPU安装、配置、测试(无需手动安装CUDA)

    其中其决定作用的是这篇文章  https://www.pugetsystems.com/labs/hpc/Install-TensorFlow-with-GPU-Support-the-Easy-Wa ...

  4. python 无法引用 tensorflow.keras_win10+anaconda安装tensorflow和keras遇到的坑小结

    win10下利用anaconda安装tensorflow和keras的教程都大同小异(针对CPU版本,我的gpu是1050TI的MAX-Q,不知为啥一直没安装成功),下面简单说下步骤. 一 Anaco ...

  5. win10+anaconda安装tensorflow和keras遇到的坑小结

    win10下利用anaconda安装tensorflow和keras的教程都大同小异(针对CPU版本,我的gpu是1050TI的MAX-Q,不知为啥一直没安装成功),下面简单说下步骤. 一 Anaco ...

  6. python机器学习系列教程——深度学习框架比较TensorFlow、Theano、Caffe、SciKit-learn、Keras

    全栈工程师开发手册 (作者:栾鹏) python教程全解 Theano Theano在深度学习框架中是祖师级的存在.Theano基于Python语言开发的,是一个擅长处理多维数组的库,这一点和nump ...

  7. ICCV 2021 | 性能炸裂的通道剪枝算法ResRep(Keras复现)

    清华大学&旷世科技 Lossless CNN Channel Pruning via Decoupling Remembering and Forgetting paper:https://a ...

  8. Keras构建用于分类任务的Transformer(Vision Transformer/VIT)

    文章目录 一.Vision Transformer (ViT)详细信息 二.Vision Transformer结构 三.Keras实现 3.1 相关包 3.2 数据读取 3.3 声明超参数 3.4 ...

  9. python预测股票 keras_使用LSTM模型预测股价基于Keras

    本期作者:Derrick Mwiti 本期翻译:HUDPinkPig 未经授权,严禁转载 编者按:本文介绍了如何使用LSTM模型进行时间序列预测.股票市场的数据由于格式规整和非常容易获得,是作为研究的 ...

最新文章

  1. 排序算法----桶排序(java版)
  2. python 搜索pdf文件中的文字_使用python查找搜索字符串在pdf文档中位于哪一页上...
  3. Design Pattern - Factory Method(C#)
  4. mysql 的S 锁和X锁的区别
  5. 解决Ubuntu无法进行SSH连接的问题(以及如何使用SSH)
  6. 百度转换经纬度为地址
  7. Java、Apache Tomcat下载与安装及环境变量配置
  8. CSS外边距(margin)重叠及防止方法
  9. JavaScript数据结构和算法简述——前言
  10. 10年老兵给程序员的10条建议! 1
  11. 【MOS】Redundant Interconnect ora.cluster_interconnect.haip (文档 ID 1210883.1)
  12. wifi抓包/苹果电脑mac book抓wifi sniffer packet
  13. leetcode 5390. 数青蛙(C++)
  14. Windows提权基本原理
  15. 艺龙深耕酒店VS携程 布局旅游全产业
  16. 测试记录2:APM32对比HK32
  17. 快速查看南京商品房销售信息
  18. 使用迅雷等下载工具下载Android SDK快速安装
  19. 在 SQL 中计算总行数的百分比
  20. vmware创建win7虚拟机

热门文章

  1. 假设检验和P值那些事
  2. OPEN(SAP) UI5 学习入门系列之二: 最佳实践练习(下)
  3. 深度学习入门系列1:多层感知器概述
  4. (67)TCL脚本命令【incr(一个参数)】
  5. ABAP BDC返回成功但是未创建单据或没有产生相应效果
  6. mysql insert 阻塞_insert遭遇阻塞
  7. datagridview 获取选中行号 数据,判断是不是选中了一行
  8. C# 移除富文本多余标签
  9. 关于如何将代码上传到gitee仓库的详细步骤
  10. HTML对表格隔行变色