import cv2
import dlib
import os
import sys
import random
# 存儲位置
output_dir ='D:/631907060224'
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)#camera= cv2.VideoCapture('C:/Users/CUNGU/Videos/Captures/wang.mp4')index =1while True:if(index <=20):#存儲20張人臉特征圖像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()>0else0y1 = d.bottom()if d.bottom()>0else0x2 = d.left()if d.left()>0else0y2 = d.right()if d.right()>0else0face = 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!')# 釋放攝像頭 release cameracamera.release()# 刪除建立的窗口 delete all the windowscv2.destroyAllWindows()break
可以看到路徑下:
之后采集對應20張圖片的68個特征點數組計算出平均特征數組:
# 從人臉圖像文件中提取人臉特征存入 CSV
#Features extraction from images and save into features_all.csv#return_128d_features() 獲取某張圖像的128D特征#compute_the_mean() 計算128D特征均值from cv2 import cv2 as cv2
import os
import dlib
from skimage import io
import csv
import numpy as np# 要讀取人臉圖像文件的路徑
path_images_from_camera ="D:/631907060224/person/"#Dlib 正向人臉檢測器
detector = dlib.get_frontal_face_detector()#Dlib 人臉預測器
predictor = dlib.shape_predictor("D:/BaiduNetdiskDownload/shape_predictor_68_face_landmarks.dat")#Dlib 人臉識別模型#Face recognition model, the object maps human faces into 128D vectors
face_rec = dlib.face_recognition_model_v1("D:/BaiduNetdiskDownload/dlib_face_recognition_resnet_model_v1.dat")# 返回單張圖像的 128D 特征
def return_128d_features(path_img):img_rd = io.imread(path_img)img_gray = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)faces =detector(img_gray,1)print("%-40s %-20s"%("檢測到人臉的圖像 / image with faces detected:", path_img),'\n')# 因為有可能截下來的人臉再去檢測,檢測不出來人臉了# 所以要確保是 檢測到人臉的人臉圖像 拿去算特征iflen(faces)!=0:shape =predictor(img_gray, faces[0])face_descriptor = face_rec.compute_face_descriptor(img_gray, shape)else:face_descriptor =0print("no face")return face_descriptor# 將文件夾中照片特征提取出來, 寫入 CSV
def return_features_mean_personX(path_faces_personX):features_list_personX =[]photos_list = os.listdir(path_faces_personX)if photos_list:for i in range(len(photos_list)):# 調用return_128d_features()得到128d特征print("%-40s %-20s"%("正在讀的人臉圖像 / image to read:", path_faces_personX +"/"+ photos_list[i]))features_128d =return_128d_features(path_faces_personX +"/"+ photos_list[i])#print(features_128d)# 遇到沒有檢測出人臉的圖片跳過if features_128d ==0:i +=1else:features_list_personX.append(features_128d)i1=str(i+1)add="D:/631907060224/feature/face_feature"+i1+".csv"print(add)with open(add,"w", newline="") as csvfile:writer1 = csv.writer(csvfile)writer1.writerow(features_128d)else:print("文件夾內圖像文件為空 / Warning: No images in "+ path_faces_personX +'/','\n')# 計算 128D 特征的均值#N x 128D ->1 x 128Dif features_list_personX:features_mean_personX = np.array(features_list_personX).mean(axis=0)else:features_mean_personX ='0'return features_mean_personX# 讀取某人所有的人臉圖像的數據
people = os.listdir(path_images_from_camera)
people.sort()with open("D:/631907060224/feature/features2_all.csv","w", newline="") as csvfile:writer = csv.writer(csvfile)for person in people:print("##### "+ person +" #####")#Get the mean/average features of face/personX, it will be a list with a length of 128Dfeatures_mean_personX =return_features_mean_personX(path_images_from_camera + person)writer.writerow(features_mean_personX)print("特征均值 / The mean of features:",list(features_mean_personX))print('\n')print("所有錄入人臉數據存入 / Save all the features of faces registered into: D:/631907060224/feature/features_all2.csv")