目的:
- 檢測(cè)出用戶路徑下所有的圖片的人像特征柬批,保存在指定目錄;
- 人像原始特征為100*100 圖片;
代碼特點(diǎn):
用自制的filewalk函數(shù)遍歷用戶目錄栈幸,并跟上了文件操作回調(diào)函數(shù)撰茎,使得代碼閱讀起來(lái)更一目了然嵌牺。
完整代碼:
import os
import matplotlib.pyplot as plt
import numpy as np
from cv2 import cv2
from skimage import color, draw, io, transform
face_cascade=cv2.CascadeClassifier()
face_cascade.load(r'C:\ProgramData\Anaconda3\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
def feature_model(full_path_file,detected_path=r'C:\Users\super\Desktop\detected'):
try:img = io.imread(full_path_file)
except:return 0
path,file = os.path.split(full_path_file)
file_name,file_postfix = os.path.splitext(file)
gray = np.array(color.rgb2gray(img)*256,dtype='uint8')
faces=face_cascade.detectMultiScale(gray)
for index,face in enumerate(faces):
x,y,w,h = face
face_detected = img[y:y+h,x:x+w,:]
face_detected = transform.resize(face_detected,(100, 100),mode='reflect')
full_path_detected_file = os.path.join(detected_path,file_name+'_%s%s'%(index,file_postfix))
plt.imsave(full_path_detected_file,face_detected)
def walk(path,callback=print):
files = os.listdir(path)
for file in files:
try:
if os.path.isdir(os.path.join(path,file)):
walk(os.path.join(path,file),callback)
else:
print(os.path.join(path,file))
callback(os.path.join(path,file))
except:pass
def main():
walk(path,feature_model)
if __name__ == "__main__":
path = r'C:\Users\super'
main()
可以改進(jìn)之處:
- 沒(méi)有指定人臉特征目錄的話就自己創(chuàng)造一個(gè)目錄,目前沒(méi)有實(shí)現(xiàn)這個(gè)功能龄糊;
- 特殊權(quán)限的文件目錄不能打開(kāi)逆粹;
- 人臉識(shí)別的原始cv2檢測(cè)器太垃圾,檢測(cè)出許多非人臉特征炫惩,所以如果照片集里有很多非人像的圖片就完全沒(méi)法用捌У!
- 非人像特征太多不能作為人臉識(shí)別原始數(shù)據(jù)诡必,請(qǐng)繼續(xù)篩選奢方;
- 依圖片集大小這個(gè)程序可能會(huì)運(yùn)行兩三個(gè)小時(shí);
- 據(jù)說(shuō)編碼不能太完美主義爸舒,不然會(huì)沒(méi)完沒(méi)了~
效果:
效果