結(jié)合OpenCV與TensorFlow進(jìn)行人臉識(shí)別的實(shí)現(xiàn)
作為新手來(lái)說(shuō),這是一個(gè)最簡(jiǎn)單的人臉識(shí)別模型,難度不大,代碼量也不算多,下面就逐一來(lái)講解,數(shù)據(jù)集的準(zhǔn)備就不多說(shuō)了,因人而異。
一. 獲取數(shù)據(jù)集的所有路徑
利用os模塊來(lái)生成一個(gè)包含所有數(shù)據(jù)路徑的list
def my_face():
path = os.listdir("./my_faces")
image_path = [os.path.join("./my_faces/",img) for img in path]
return image_path
def other_face():
path = os.listdir("./other_faces")
image_path = [os.path.join("./other_faces/",img) for img in path]
return image_path
image_path = my_face().__add__(other_face()) #將兩個(gè)list合并成為一個(gè)list
二. 構(gòu)造標(biāo)簽
標(biāo)簽的構(gòu)造較為簡(jiǎn)單,1表示本人,0表示其他人。
label_my= [1 for i in my_face()] label_other = [0 for i in other_face()] label = label_my.__add__(label_other) #合并兩個(gè)list
三.構(gòu)造數(shù)據(jù)集
利用tf.data.Dataset.from_tensor_slices()構(gòu)造數(shù)據(jù)集,
def preprocess(x,y): x = tf.io.read_file(x) #讀取數(shù)據(jù) x = tf.image.decode_jpeg(x,channels=3) #解碼成jpg格式的數(shù)據(jù) x = tf.cast(x,tf.float32) / 255.0 #歸一化 y = tf.convert_to_tensor(y) #轉(zhuǎn)成tensor return x,y data = tf.data.Dataset.from_tensor_slices((image_path,label)) data_loader = data.repeat().shuffle(5000).map(preprocess).batch(128).prefetch(1)
四.構(gòu)造模型
class CNN_WORK(Model):
def __init__(self):
super(CNN_WORK,self).__init__()
self.conv1 = layers.Conv2D(32,kernel_size=5,activation=tf.nn.relu)
self.maxpool1 = layers.MaxPool2D(2,strides=2)
self.conv2 = layers.Conv2D(64,kernel_size=3,activation=tf.nn.relu)
self.maxpool2 = layers.MaxPool2D(2,strides=2)
self.flatten = layers.Flatten()
self.fc1 = layers.Dense(1024)
self.dropout = layers.Dropout(rate=0.5)
self.out = layers.Dense(2)
def call(self,x,is_training=False):
x = self.conv1(x)
x = self.maxpool1(x)
x = self.conv2(x)
x = self.maxpool2(x)
x = self.flatten(x)
x = self.fc1(x)
x = self.dropout(x,training=is_training)
x = self.out(x)
if not is_training:
x = tf.nn.softmax(x)
return x
model = CNN_WORK()

五.定義損失函數(shù),精度函數(shù),優(yōu)化函數(shù)
def cross_entropy_loss(x,y): y = tf.cast(y,tf.int64) loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=x) return tf.reduce_mean(loss) def accuracy(y_pred,y_true): correct_pred = tf.equal(tf.argmax(y_pred,1),tf.cast(y_true,tf.int64)) return tf.reduce_mean(tf.cast(correct_pred,tf.float32),axis=-1) optimizer = tf.optimizers.SGD(0.002)
六.開(kāi)始跑步我們的模型
def run_optimizer(x,y):
with tf.GradientTape() as g:
pred = model(x,is_training=True)
loss = cross_entropy_loss(pred,y)
training_variabel = model.trainable_variables
gradient = g.gradient(loss,training_variabel)
optimizer.apply_gradients(zip(gradient,training_variabel))
model.save_weights("face_weight") #保存模型
最后跑的準(zhǔn)確率還是挺高的。

七.openCV登場(chǎng)
最后利用OpenCV的人臉檢測(cè)模塊,將檢測(cè)到的人臉?biāo)腿氲轿覀冇?xùn)練好了的模型中進(jìn)行預(yù)測(cè)根據(jù)預(yù)測(cè)的結(jié)果進(jìn)行標(biāo)識(shí)。
cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('C:\\Users\Wuhuipeng\AppData\Local\Programs\Python\Python36\Lib\site-packages\cv2\data/haarcascade_frontalface_alt.xml')
while True:
ret,frame = cap.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(5,5))
for (x,y,z,t) in faces:
img = frame[x:x+z,y:y+t]
try:
img = cv2.resize(img,(64,64))
img = tf.cast(img,tf.float32) / 255.0
img = tf.reshape(img,[-1,64,64,3])
pred = model(img)
pred = tf.argmax(pred,axis=1).numpy()
except:
pass
if(pred[0]==1):
cv2.putText(frame,"wuhuipeng",(x-10,y-10),cv2.FONT_HERSHEY_SIMPLEX,1.2,(255,255,0),2)
cv2.rectangle(frame,(x,y),(x+z,y+t),(0,255,0),2)
cv2.imshow('find faces',frame)
if cv2.waitKey(1)&0xff ==ord('q'):
break
cap.release()
cv2.destroyAllWindows()
完整代碼地址github.
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- opencv 做人臉識(shí)別 opencv 人臉匹配分析
- python+opencv實(shí)現(xiàn)的簡(jiǎn)單人臉識(shí)別代碼示例
- python使用opencv進(jìn)行人臉識(shí)別
- OpenCV實(shí)現(xiàn)人臉識(shí)別
- 基于python3 OpenCV3實(shí)現(xiàn)靜態(tài)圖片人臉識(shí)別
- python opencv3實(shí)現(xiàn)人臉識(shí)別(windows)
- python調(diào)用OpenCV實(shí)現(xiàn)人臉識(shí)別功能
- Python基于Opencv來(lái)快速實(shí)現(xiàn)人臉識(shí)別過(guò)程詳解(完整版)
- Python opencv實(shí)現(xiàn)人眼/人臉識(shí)別以及實(shí)時(shí)打碼處理
- OpenCV實(shí)現(xiàn)人臉識(shí)別簡(jiǎn)單程序
相關(guān)文章
小白學(xué)Python之實(shí)現(xiàn)OCR識(shí)別
將圖片翻譯成文字一般被稱為光學(xué)文字識(shí)別(Optical Character Recognition,OCR),這篇文章主要給大家介紹了關(guān)于Python實(shí)現(xiàn)OCR識(shí)別的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08
使用python matploblib庫(kù)繪制準(zhǔn)確率,損失率折線圖
這篇文章主要介紹了使用python matploblib庫(kù)繪制準(zhǔn)確率,損失率折線圖,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python光學(xué)仿真從Maxwell方程組到波動(dòng)方程矢量算法理解學(xué)習(xí)
這篇文章主要為大家介紹了Python光學(xué)仿真從Maxwell方程組到波動(dòng)方程算法的理解學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
解決pycharm運(yùn)行出錯(cuò),代碼正確結(jié)果不顯示的問(wèn)題
今天小編就為大家分享一篇解決pycharm運(yùn)行出錯(cuò),代碼正確結(jié)果不顯示的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
Python實(shí)現(xiàn)自動(dòng)化對(duì)Word文檔添加或移除行號(hào)
Word文檔中的行號(hào)(行編號(hào))功能是對(duì)于精細(xì)化的文檔編輯以及解析非常有用的功能,添加行號(hào)能夠極大地提升文檔的可讀性和定位效率,本文將介紹如何使用Python來(lái)實(shí)現(xiàn)自動(dòng)化對(duì)Word文檔添加或移除行號(hào),為文檔處理工作帶來(lái)便捷,需要的朋友可以參考下2024-07-07
Python關(guān)于版本升級(jí)與包的維護(hù)方式
這篇文章主要介紹了Python關(guān)于版本升級(jí)與包的維護(hù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Python快速實(shí)現(xiàn)簡(jiǎn)易貪吃蛇小游戲的示例代碼
貪吃蛇(也叫做貪食蛇)游戲是一款休閑益智類游戲,有PC和手機(jī)等多平臺(tái)版本。既簡(jiǎn)單又耐玩。本文將利用Python語(yǔ)言快速實(shí)現(xiàn)簡(jiǎn)易貪吃蛇小游戲,感興趣的可以嘗試一下2022-10-10

