訓練一個神經網絡 能讓她認得我

寫個神經網絡,讓她認得我`(?????)(Tensorflow,opencv,dlib,cnn,人臉識別)

這段時間正在學習tensorflow的卷積神經網絡部分,為了對卷積神經網絡能夠有一個更深的了解,自己動手實現一個例程是比較好的方式,所以就選了一個這樣比較有點意思的項目。

項目的github地址:github?喜歡的話就給個Star吧。

想要她認得我,就需要給她一些我的照片,讓她記住我的人臉特征,為了讓她區分我和其他人,還需要給她一些其他人的照片做參照,所以就需要兩組數據集來讓她學習,如果想讓她多認識幾個人,那多給她幾組圖片集學習就可以了。下面就開始讓我們來搭建這個能認識我的"她"。

運行環境

下面為軟件的運行搭建系統環境。

系統: window或linux

軟件: python 3.x 、 tensorflow

python支持庫:

tensorflow:

pip install tensorflow      #cpu版本
pip install rensorflow-gpu  #gpu版本,需要cuda與cudnn的支持,不清楚的可以選擇cpu版

numpy:

pip install numpy

opencv:

pip install opencv-python

dlib:

pip install dlib

獲取本人圖片集

獲取本人照片的方式當然是拍照了,我們需要通過程序來給自己拍照,如果你自己有照片,也可以用那些現成的照片,但前提是你的照片足夠多。這次用到的照片數是10000張,程序運行后,得坐在電腦面前不停得給自己的臉擺各種姿勢,這樣可以提高訓練后識別自己的成功率,在程序中加入了隨機改變對比度與亮度的模塊,也是為了提高照片樣本的多樣性。

程序中使用的是dlib來識別人臉部分,也可以使用opencv來識別人臉,在實際使用過程中,dlib的識別效果比opencv的好,但opencv識別的速度會快很多,獲取10000張人臉照片的情況下,dlib大約花費了1小時,而opencv的花費時間大概只有20分鐘。opencv可能會識別一些奇怪的部分,所以綜合考慮之后我使用了dlib來識別人臉。

get_my_faces.py

import cv2
import dlib
import os
import sys
import randomoutput_dir = './my_faces'
size = 64if not os.path.exists(output_dir):os.makedirs(output_dir)# 改變圖片的亮度與對比度
def relight(img, light=1, bias=0):w = img.shape[1]h = img.shape[0]#image = []for i in range(0,w):for j in range(0,h):for c in range(3):tmp = int(img[j,i,c]*light + bias)if tmp > 255:tmp = 255elif tmp < 0:tmp = 0img[j,i,c] = tmpreturn img#使用dlib自帶的frontal_face_detector作為我們的特征提取器
detector = dlib.get_frontal_face_detector()
# 打開攝像頭 參數為輸入流,可以為攝像頭或視頻文件
camera = cv2.VideoCapture(0)index = 1
while True:if (index <= 10000):print('Being processed picture %s' % index)# 從攝像頭讀取照片success, img = camera.read()# 轉為灰度圖片gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 使用detector進行人臉檢測dets = detector(gray_img, 1)for i, d in enumerate(dets):x1 = d.top() if d.top() > 0 else 0y1 = d.bottom() if d.bottom() > 0 else 0x2 = d.left() if d.left() > 0 else 0y2 = d.right() if d.right() > 0 else 0face = img[x1:y1,x2:y2]# 調整圖片的對比度與亮度, 對比度與亮度值都取隨機數,這樣能增加樣本的多樣性face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))face = cv2.resize(face, (size,size))cv2.imshow('image', face)cv2.imwrite(output_dir+'/'+str(index)+'.jpg', face)index += 1key = cv2.waitKey(30) & 0xffif key == 27:breakelse:print('Finished!')break

在這里我也給出一個opencv來識別人臉的代碼示例:

import cv2
import os
import sys
import randomout_dir = './my_faces'
if not os.path.exists(out_dir):os.makedirs(out_dir)# 改變亮度與對比度
def relight(img, alpha=1, bias=0):w = img.shape[1]h = img.shape[0]#image = []for i in range(0,w):for j in range(0,h):for c in range(3):tmp = int(img[j,i,c]*alpha + bias)if tmp > 255:tmp = 255elif tmp < 0:tmp = 0img[j,i,c] = tmpreturn img# 獲取分類器
haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')# 打開攝像頭 參數為輸入流,可以為攝像頭或視頻文件
camera = cv2.VideoCapture(0)n = 1
while 1:if (n <= 10000):print('It`s processing %s image.' % n)# 讀幀success, img = camera.read()gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)faces = haar.detectMultiScale(gray_img, 1.3, 5)for f_x, f_y, f_w, f_h in faces:face = img[f_y:f_y+f_h, f_x:f_x+f_w]face = cv2.resize(face, (64,64))'''if n % 3 == 1:face = relight(face, 1, 50)elif n % 3 == 2:face = relight(face, 0.5, 0)'''face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))cv2.imshow('img', face)cv2.imwrite(out_dir+'/'+str(n)+'.jpg', face)n+=1key = cv2.waitKey(30) & 0xffif key == 27:breakelse:break

獲取其他人臉圖片集

需要收集一個其他人臉的圖片集,只要不是自己的人臉都可以,可以在網上找到,這里我給出一個我用到的圖片集:

網站地址:http://vis-www.cs.umass.edu/lfw/

圖片集下載:http://vis-www.cs.umass.edu/lfw/lfw.tgz

先將下載的圖片集,解壓到項目目錄下的input_img目錄下,也可以自己指定目錄(修改代碼中的input_dir變量)

接下來使用dlib來批量識別圖片中的人臉部分,并保存到指定目錄下

set_other_people.py

# -*- codeing: utf-8 -*-
import sys
import os
import cv2
import dlibinput_dir = './input_img'
output_dir = './other_faces'
size = 64if not os.path.exists(output_dir):os.makedirs(output_dir)#使用dlib自帶的frontal_face_detector作為我們的特征提取器
detector = dlib.get_frontal_face_detector()index = 1
for (path, dirnames, filenames) in os.walk(input_dir):for filename in filenames:if filename.endswith('.jpg'):print('Being processed picture %s' % index)img_path = path+'/'+filename# 從文件讀取圖片img = cv2.imread(img_path)# 轉為灰度圖片gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 使用detector進行人臉檢測 dets為返回的結果dets = detector(gray_img, 1)#使用enumerate 函數遍歷序列中的元素以及它們的下標#下標i即為人臉序號#left:人臉左邊距離圖片左邊界的距離 ;right:人臉右邊距離圖片左邊界的距離 #top:人臉上邊距離圖片上邊界的距離 ;bottom:人臉下邊距離圖片上邊界的距離for i, d in enumerate(dets):x1 = d.top() if d.top() > 0 else 0y1 = d.bottom() if d.bottom() > 0 else 0x2 = d.left() if d.left() > 0 else 0y2 = d.right() if d.right() > 0 else 0# img[y:y+h,x:x+w]face = img[x1:y1,x2:y2]# 調整圖片的尺寸face = cv2.resize(face, (size,size))cv2.imshow('image',face)# 保存圖片cv2.imwrite(output_dir+'/'+str(index)+'.jpg', face)index += 1key = cv2.waitKey(30) & 0xffif key == 27:sys.exit(0)

other-face

這個項目用到的圖片數是10000張左右,如果是自己下載的圖片集,控制一下圖片的數量避免數量不足,或圖片過多帶來的內存不夠與運行緩慢。

訓練模型

有了訓練數據之后,通過cnn來訓練數據,就可以讓她記住我的人臉特征,學習怎么認識我了。

train_faces.py

import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_splitmy_faces_path = './my_faces'
other_faces_path = './other_faces'
size = 64imgs = []
labs = []def getPaddingSize(img):h, w, _ = img.shapetop, bottom, left, right = (0,0,0,0)longest = max(h, w)if w < longest:tmp = longest - w# //表示整除符號left = tmp // 2right = tmp - leftelif h < longest:tmp = longest - htop = tmp // 2bottom = tmp - topelse:passreturn top, bottom, left, rightdef readData(path , h=size, w=size):for filename in os.listdir(path):if filename.endswith('.jpg'):filename = path + '/' + filenameimg = cv2.imread(filename)top,bottom,left,right = getPaddingSize(img)# 將圖片放大, 擴充圖片邊緣部分img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0,0,0])img = cv2.resize(img, (h, w))imgs.append(img)labs.append(path)readData(my_faces_path)
readData(other_faces_path)
# 將圖片數據與標簽轉換成數組
imgs = np.array(imgs)
labs = np.array([[0,1] if lab == my_faces_path else [1,0] for lab in labs])
# 隨機劃分測試集與訓練集
train_x,test_x,train_y,test_y = train_test_split(imgs, labs, test_size=0.05, random_state=random.randint(0,100))
# 參數:圖片數據的總數,圖片的高、寬、通道
train_x = train_x.reshape(train_x.shape[0], size, size, 3)
test_x = test_x.reshape(test_x.shape[0], size, size, 3)
# 將數據轉換成小于1的數
train_x = train_x.astype('float32')/255.0
test_x = test_x.astype('float32')/255.0print('train size:%s, test size:%s' % (len(train_x), len(test_x)))
# 圖片塊,每次取100張圖片
batch_size = 100
num_batch = len(train_x) // batch_sizex = tf.placeholder(tf.float32, [None, size, size, 3])
y_ = tf.placeholder(tf.float32, [None, 2])keep_prob_5 = tf.placeholder(tf.float32)
keep_prob_75 = tf.placeholder(tf.float32)def weightVariable(shape):init = tf.random_normal(shape, stddev=0.01)return tf.Variable(init)def biasVariable(shape):init = tf.random_normal(shape)return tf.Variable(init)def conv2d(x, W):return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')def maxPool(x):return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')def dropout(x, keep):return tf.nn.dropout(x, keep)def cnnLayer():# 第一層W1 = weightVariable([3,3,3,32]) # 卷積核大小(3,3), 輸入通道(3), 輸出通道(32)b1 = biasVariable([32])# 卷積conv1 = tf.nn.relu(conv2d(x, W1) + b1)# 池化pool1 = maxPool(conv1)# 減少過擬合,隨機讓某些權重不更新drop1 = dropout(pool1, keep_prob_5)# 第二層W2 = weightVariable([3,3,32,64])b2 = biasVariable([64])conv2 = tf.nn.relu(conv2d(drop1, W2) + b2)pool2 = maxPool(conv2)drop2 = dropout(pool2, keep_prob_5)# 第三層W3 = weightVariable([3,3,64,64])b3 = biasVariable([64])conv3 = tf.nn.relu(conv2d(drop2, W3) + b3)pool3 = maxPool(conv3)drop3 = dropout(pool3, keep_prob_5)# 全連接層Wf = weightVariable([8*16*32, 512])bf = biasVariable([512])drop3_flat = tf.reshape(drop3, [-1, 8*16*32])dense = tf.nn.relu(tf.matmul(drop3_flat, Wf) + bf)dropf = dropout(dense, keep_prob_75)# 輸出層Wout = weightVariable([512,2])bout = weightVariable([2])#out = tf.matmul(dropf, Wout) + boutout = tf.add(tf.matmul(dropf, Wout), bout)return outdef cnnTrain():out = cnnLayer()cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y_))train_step = tf.train.AdamOptimizer(0.01).minimize(cross_entropy)# 比較標簽是否相等,再求的所有數的平均值,tf.cast(強制轉換類型)accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(out, 1), tf.argmax(y_, 1)), tf.float32))# 將loss與accuracy保存以供tensorboard使用tf.summary.scalar('loss', cross_entropy)tf.summary.scalar('accuracy', accuracy)merged_summary_op = tf.summary.merge_all()# 數據保存器的初始化saver = tf.train.Saver()with tf.Session() as sess:sess.run(tf.global_variables_initializer())summary_writer = tf.summary.FileWriter('./tmp', graph=tf.get_default_graph())for n in range(10):# 每次取128(batch_size)張圖片for i in range(num_batch):batch_x = train_x[i*batch_size : (i+1)*batch_size]batch_y = train_y[i*batch_size : (i+1)*batch_size]# 開始訓練數據,同時訓練三個變量,返回三個數據_,loss,summary = sess.run([train_step, cross_entropy, merged_summary_op],feed_dict={x:batch_x,y_:batch_y, keep_prob_5:0.5,keep_prob_75:0.75})summary_writer.add_summary(summary, n*num_batch+i)# 打印損失print(n*num_batch+i, loss)if (n*num_batch+i) % 100 == 0:# 獲取測試數據的準確率acc = accuracy.eval({x:test_x, y_:test_y, keep_prob_5:1.0, keep_prob_75:1.0})print(n*num_batch+i, acc)# 準確率大于0.98時保存并退出if acc > 0.98 and n > 2:saver.save(sess, './train_faces.model', global_step=n*num_batch+i)sys.exit(0)print('accuracy less 0.98, exited!')cnnTrain()

訓練之后的數據會保存在當前目錄下。

使用模型進行識別

最后就是讓她認識我了,很簡單,只要運行程序,讓攝像頭拍到我的臉,她就可以輕松地識別出是不是我了。

is_my_face.py

output = cnnLayer()  
predict = tf.argmax(output, 1)  saver = tf.train.Saver()  
sess = tf.Session()  
saver.restore(sess, tf.train.latest_checkpoint('.'))  def is_my_face(image):  res = sess.run(predict, feed_dict={x: [image/255.0], keep_prob_5:1.0, keep_prob_75: 1.0})  if res[0] == 1:  return True  else:  return False  #使用dlib自帶的frontal_face_detector作為我們的特征提取器
detector = dlib.get_frontal_face_detector()cam = cv2.VideoCapture(0)  while True:  _, img = cam.read()  gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)dets = detector(gray_image, 1)if not len(dets):#print('Can`t get face.')cv2.imshow('img', img)key = cv2.waitKey(30) & 0xff  if key == 27:sys.exit(0)for i, d in enumerate(dets):x1 = d.top() if d.top() > 0 else 0y1 = d.bottom() if d.bottom() > 0 else 0x2 = d.left() if d.left() > 0 else 0y2 = d.right() if d.right() > 0 else 0face = img[x1:y1,x2:y2]# 調整圖片的尺寸face = cv2.resize(face, (size,size))print('Is this my face? %s' % is_my_face(face))cv2.rectangle(img, (x2,x1),(y2,y1), (255,0,0),3)cv2.imshow('image',img)key = cv2.waitKey(30) & 0xffif key == 27:sys.exit(0)sess.close() 

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/387216.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387216.shtml
英文地址,請注明出處:http://en.pswp.cn/news/387216.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據結構03棧和隊列

第三章棧和隊列 STL棧&#xff1a;stack http://blog.csdn.net/weixin_37289816/article/details/54773495隊列&#xff1a;queue http://blog.csdn.net/weixin_37289816/article/details/54773581priority_queue http://blog.csdn.net/weixin_37289816/article/details/5477…

Java動態編譯執行

在某些情況下&#xff0c;我們需要動態生成java代碼&#xff0c;通過動態編譯&#xff0c;然后執行代碼。JAVA API提供了相應的工具&#xff08;JavaCompiler&#xff09;來實現動態編譯。下面我們通過一個簡單的例子介紹&#xff0c;如何通過JavaCompiler實現java代碼動態編譯…

樹莓派pwm驅動好盈電調及伺服電機

本文講述如何通過樹莓派的硬件PWM控制好盈電調來驅動RC車子的前進后退&#xff0c;以及如何驅動伺服電機來控制車子轉向。 1. 好盈電調簡介 車子上的電調型號為&#xff1a;WP-10BLS-A-RTR&#xff0c;在好盈官網并沒有搜到對應手冊&#xff0c;但找到一份通用RC競速車的電調使…

數據結構04串

第四章 串 STL&#xff1a;string http://blog.csdn.net/weixin_37289816/article/details/54716009計算機上非數值處理的對象基本上是字符串數據。 在不同類型的應用中&#xff0c;字符串具有不同的特點&#xff0c;要有效的實現字符串的處理&#xff0c;必須選用合適的存儲…

CAS單點登錄原理解析

CAS單點登錄原理解析 SSO英文全稱Single Sign On&#xff0c;單點登錄。SSO是在多個應用系統中&#xff0c;用戶只需要登錄一次就可以訪問所有相互信任的應用系統。CAS是一種基于http協議的B/S應用系統單點登錄實現方案&#xff0c;認識CAS之前首先要熟悉http協議、Session與Co…

JDK1.6版添加了新的ScriptEngine類,允許用戶直接執行js代碼。

JDK1.6版添加了新的ScriptEngine類&#xff0c;允許用戶直接執行js代碼。在Java中直接調用js代碼 不能調用瀏覽器中定義的js函數&#xff0c;會拋出異常提示ReferenceError: “alert” is not defined。[java] view plaincopypackage com.sinaapp.manjushri; import javax.sc…

數據結構05數組和廣義表

第五章 數組 和 廣義表 數組和廣義表可以看成是線性表在下述含義上的擴展&#xff1a;表中的數據元素本身也是一個數據結構。 5.1 數組的定義 n維數組中每個元素都受著n個關系的約束&#xff0c;每個元素都有一個直接后繼元素。 可以把二維數組看成是這樣一個定長線性表&…

k8s的ingress使用

ingress 可以配置一個入口來提供k8s上service從外部來訪問的url、負載平衡流量、終止SSL和提供基于名稱的虛擬主機。 配置ingress的yaml&#xff1a; 要求域名解析無誤 要求service對應的pod正常 一、test1.domain.com --> service1:8080 apiVersion: extensions/v1beta1…

JDK1.8中如何用ScriptEngine動態執行JS

JDK1.8中如何用ScriptEngine動態執行JS jdk1.6開始就提供了動態腳本語言諸如JavaScript動態的支持。這無疑是一個很好的功能&#xff0c;畢竟Java的語法不是適合成為動態語言。而JDK通過執行JavaScript腳本可以彌補這一不足。這也符合“Java虛擬機不僅僅是Java一種語言的虛擬機…

數據結構06樹和二叉樹

第六章 樹和二叉樹 6.1 樹的定義和基本術語 樹 Tree 是n個結點的有限集。 任意一棵非空樹中&#xff1a; &#xff08;1&#xff09;有且僅有一個特定的稱為根&#xff08;root&#xff09;的結點&#xff1b; &#xff08;2&#xff09;當n>1時&#xff0c;其余結點可…

2019.03.20 mvt,Django分頁

MVT模式 MVT各部分的功能: M全拼為Model&#xff0c;與MVC中的M功能相同&#xff0c;負責和數據庫交互&#xff0c;進行數據處理。 V全拼為View&#xff0c;與MVC中的C功能相同&#xff0c;接收請求&#xff0c;進行業務處理&#xff0c;返回響應。 T全拼為Tem…

CountDownLatch,CyclicBarrier和Semaphore

在java 1.5中&#xff0c;提供了一些非常有用的輔助類來幫助我們進行并發編程&#xff0c;比如CountDownLatch&#xff0c;CyclicBarrier和Semaphore&#xff0c;今天我們就來學習一下這三個輔助類的用法。以下是本文目錄大綱&#xff1a;一.CountDownLatch用法二.CyclicBarrie…

數據結構07排序

第十章內部排序 10.1 概述 排序就是把一組數據按關鍵字的大小有規律地排列。經過排序的數據更易于查找。 排序前KiKj&#xff0c;且Ki在前: 排序方法是穩定的&#xff0c;若排序后Ki在前&#xff1b; 排序方法是不穩定的&#xff0c;如排序后Kj在前。 分類&#xff1a; 內…

數據結構08查找

第九章 查找 另一種在實際應用中大量使用的數據結構--查找表。 所謂查找&#xff0c;即為在一個含有眾多的數據元素的查找表中找出某個“特定的”數據元素。 查找表 search table 是由同一類型的數據元素構成的集合。集合中的數據元素之間存在著完全松散的關系&#xff0c;故…

下載Centos7 64位鏡像

下載Centos7 64位鏡像 1.打開Centos官網 打開Centos官方網站地址&#xff1a;https://www.centos.org/&#xff0c;點擊Get CentOS Now 2.點擊Minimal ISO鏡像 Minimal ISO鏡像&#xff0c;與DVD ISO鏡像的差別有很多&#xff0c;這里只說兩點 1.Minimal ISO類似于Windows的純凈…

[Objective-C語言教程]結構體(17)

Objective-C數組可定義包含多個相同類型的數據項的變量類型&#xff0c;但結構體是Objective-C編程中的另一個用戶定義數據類型&#xff0c;它可組合不同類型的數據項。 結構體用于表示記錄&#xff0c;假設要圖書館中跟蹤書籍信息。可能希望跟蹤每本書的以下屬性 - 標題作者學…

Scala01入門

第1章 可伸展的語言 Scala應用范圍廣&#xff0c;從編寫腳本&#xff0c;到建立大型系統。 運行在標準Java平臺上&#xff0c;與Java庫無縫交互。 更能發揮力量的地方&#xff1a;建立大型系統或可重用控件的架構。 將面向對象和函數式編程加入到靜態類型語言。 在Scala中&a…

架構師之路17年精選80篇

【架構必備】 《互聯網架構如何實現“高并發”》4W 《TCP接入層的負載均衡、高可用、擴展性架構設計》2.2W 《配置中心架構設計演進》1.7W 《跨公網調用的大坑與架構優化》1.4W 《DNS在架構設計中的巧用》1.9W 《消息如何在網絡上安全傳輸》1.2W 《10W定時任務&#xff0c;如何…

iphone手機型號獲取

#import <sys/utsname.h> //手機型號 NSString *device [self iphoneType]; (NSString *)iphoneType { struct utsname systemInfo; uname(&systemInfo); NSString *platform [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]; if…

Java網絡01基本網絡概念

協議 Protocol&#xff1a;明確規則 &#xff08;1&#xff09;地址格式&#xff1b; &#xff08;2&#xff09;數據如何分包&#xff1b; ... TCP/IP四層模型&#xff1a; 應用層 HTTP SMTP POP IMAP 傳輸層 TCP UDP 網際層 IP 主機網絡層 host to host layer 數模、…