做者|Nagesh Singh Chauhan
編譯|Flin
來源|towardsdatasciencepython
愈來愈多的應用程序與年齡和性別的自動分類相關,特別是自從社交平臺和社交媒體興起以來。儘管如此,現有的方法在真實圖像上的性能仍然明顯不足,特別是與最近報道的與人臉識別相關的任務在性能上的巨大飛躍相比。——使用卷積神經網絡進行年齡和性別分類(https://talhassner.github.io/...)git
年齡和性別是人臉的兩個重要屬性,在社會交往中起着很是基礎的做用,使得從單我的臉圖像中估計年齡和性別成爲智能應用中的一項重要任務,如訪問控制、人機交互、執法、營銷智能以及視覺監控等。github
真實世界用例:web
最近我遇到了Quividi,它是一我的工智能軟件應用程序,用於根據在線人臉分析檢測通過的用戶的年齡和性別,並根據目標受衆自動開始播放廣告。算法
另外一個例子多是AgeBot,它是一個Android應用程序,經過人臉識別從照片中肯定你的年齡。它能夠猜想你的年齡和性別,同時也能夠在一張照片中找到多張臉,並估計每張臉的年齡。網絡
受上述用例的啓發,咱們將在本文中構建一個簡單的年齡和性別檢測模型。因此讓咱們從咱們的用例開始:框架
用例——咱們將作一些人臉識別,人臉檢測的工做,並且,咱們將使用CNN(卷積神經網絡)從youtube視頻中預測年齡和性別,只要視頻URL是能夠用的,你就不須要下載視頻。有趣的部分是CNN在視頻網址上用於年齡和性別預測。機器學習
要求:
pip install OpenCV-python
numpy
pip install pafy
pip install youtube_dl(瞭解更多關於youtube-dl的信息:https://rg3.github.io/youtube...)ide
pafy:pafy庫用於檢索YouTube內容和元數據(如標題、分級、觀看次數、持續時間、分級、做者、縮略圖、關鍵字等)。更多有關pafy,點擊網址:https://pypi.org/project/pafy/函數
讓咱們檢查一個樣本:
import pafy url = 'https://www.youtube.com/watch?v=c07IsbSNqfI&feature=youtu.be' vPafy = pafy.new(url) print vPafy.title print vPafy.rating print vPafy.viewcount print vPafy.author print vPafy.length print vPafy.description
Testing file uploads with Postman (multipart/form-data) 4.87096786499 11478 Valentin Despa 1688 ➡️➡️➡️ 📢 Check my online course on Postman. Get it for only $10 (limited supply): https://www.udemy.com/postman-the-complete-guide/?couponCode=YOUTUBE10 I will show you how to debug an upload script and demonstrate it with a tool that can make requests encoded as "multipart/form-data" so that you can send also a file. After this, we will go even further and write tests and begin automating the process. Here is the Git repository containing the files used for this tutorial: https://github.com/vdespa/postman-testing-file-uploads
要遵循的步驟:
1.從YouTube獲取視頻網址:
獲取Youtube視頻URL並嘗試使用pafy獲取視頻的屬性,如上所述。
2. 使用Haar級聯人臉檢測:
這是咱們大多數人至少據說過的一部分。OpenCV/JavaCV提供了直接的方法來導入Haar級聯並使用它們來檢測人臉。我不會深刻解釋這一部分。大家能夠參考我以前的文章來了解更多關於使用OpenCV進行人臉檢測的信息。
3. CNN的性別識別:
使用OpenCV的fisherfaces
實現的性別識別很是流行,大家中的一些人可能也嘗試過或閱讀過它。可是,在這個例子中,我將使用不一樣的方法來識別性別。2015年,以色列兩名研究人員Gil Levi和Tal Hassner引入了這種方法。我在這個例子中使用了他們訓練的CNN模型。咱們將使用OpenCV的dnn包,它表明「深度神經網絡」。
在dnn包中,OpenCV提供了一個名爲Net的類,能夠用來填充神經網絡。此外,這些軟件包還支持從知名的深度學習框架(如caffe、tensorflow和torch)導入神經網絡模型。我前面提到的研究人員已經將他們的CNN模型發佈爲caffe模型。所以,咱們將使用CaffeImporter將該模型導入到咱們的應用程序中。
4. CNN的年齡識別
這與性別識別部分很類似,只是對應的prototxt文件和caffe模型文件是"deploy_agenet.prototxt"和」age_net.caffemodel」. 此外,CNN在該CNN中的輸出層(機率層)由8個年齡層的8個值組成(「0-2」、「4-6」、「8-13」、「15-20」、「25-32」、「38-43」、「48-53」和「60-」)
Caffe模型具備2個相關文件,
1. prototxt: 這裏是CNN的定義。這個文件定義了神經網絡的各個層,每一個層的輸入、輸出和函數。
2. caffemodel: 包含訓練神經網絡(訓練模型)的信息。
從這裏(https://talhassner.github.io/...) 下載.prtoxt和.caffemodel。
從這裏(https://github.com/opencv/ope...) 下載用於人臉檢測的haar級聯。
讓咱們開始編碼咱們的模型吧。
源代碼:
import cv2 import numpy as np import pafy #url of the video to predict Age and gender url = 'https://www.youtube.com/watch?v=c07IsbSNqfI&feature=youtu.be' vPafy = pafy.new(url) play = vPafy.getbest(preftype="mp4") cap = cv2.VideoCapture(play.url) cap.set(3, 480) #set width of the frame cap.set(4, 640) #set height of the frame MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746) age_list = ['(0, 2)', '(4, 6)', '(8, 12)', '(15, 20)', '(25, 32)', '(38, 43)', '(48, 53)', '(60, 100)'] gender_list = ['Male', 'Female'] def load_caffe_models(): age_net = cv2.dnn.readNetFromCaffe('deploy_age.prototxt', 'age_net.caffemodel') gender_net = cv2.dnn.readNetFromCaffe('deploy_gender.prototxt', 'gender_net.caffemodel') return(age_net, gender_net) def video_detector(age_net, gender_net): font = cv2.FONT_HERSHEY_SIMPLEX while True: ret, image = cap.read() face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.1, 5) if(len(faces)>0): print("Found {} faces".format(str(len(faces)))) for (x, y, w, h )in faces: cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 0), 2) #Get Face face_img = image[y:y+h, h:h+w].copy() blob = cv2.dnn.blobFromImage(face_img, 1, (227, 227), MODEL_MEAN_VALUES, swapRB=False) #Predict Gender gender_net.setInput(blob) gender_preds = gender_net.forward() gender = gender_list[gender_preds[0].argmax()] print("Gender : " + gender) #Predict Age age_net.setInput(blob) age_preds = age_net.forward() age = age_list[age_preds[0].argmax()] print("Age Range: " + age) overlay_text = "%s %s" % (gender, age) cv2.putText(image, overlay_text, (x, y), font, 1, (255, 255, 255), 2, cv2.LINE_AA) cv2.imshow('frame', image) #0xFF is a hexadecimal constant which is 11111111 in binary. if cv2.waitKey(1) & 0xFF == ord('q'): break if __name__ == "__main__": age_net, gender_net = load_caffe_models() video_detector(age_net, gender_net)
如今讓咱們一塊兒來理解代碼:
步驟1:導入全部必需的庫。
import cv2 import numpy as np import pafy
步驟2:獲取Youtube視頻URL並建立一個對象「play」,該對象包含webm/mp4格式的視頻的最佳分辨率。
url = 'https://www.youtube.com/watch?v=c07IsbSNqfI&feature=youtu.be' vPafy = pafy.new(url) play = vPafy.getbest(preftype="mp4")
第三步:一般,咱們必須用相機捕捉現場的視頻流。OpenCV提供了一個很是簡單的接口。咱們能夠從相機中捕捉視頻,將其轉換成灰度視頻並顯示出來。只是一個簡單的開始。
要捕獲視頻,須要建立視頻捕獲對象。它的參數能夠是設備索引或視頻文件的名稱。設備索引只是指定哪一個攝像機的數字。一般會鏈接一個攝像頭(如個人狀況)。因此我只傳遞0(或-1)。能夠經過傳遞1等來選擇第二個攝影機。以後,你能夠逐幀捕獲。
cap = cv2.VideoCapture(0) #if you are using webcam
但在個人例子中,我正在讀取一個在線視頻URL,爲此,我將把「play」對象傳遞給VideoCapture()。
cap = cv2.VideoCapture(play.url)
步驟4:使用set()設置視頻幀的高度和寬度。cap.set(propId, value),這裏3是寬度的propertyId,4是高度的propertyId。
cap.set(3, 480) #set width of the frame cap.set(4, 640) #set height of the frame
步驟5:建立3個單獨的列表,用於存儲Model_Mean_值、年齡和性別。
MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746) age_list = ['(0, 2)', '(4, 6)', '(8, 12)', '(15, 20)', '(25, 32)', '(38, 43)', '(48, 53)', '(60, 100)'] gender_list = ['Male', 'Female']
第六步:我定義了一個函數來加載caffemodel和prototxt的年齡和性別檢測器,這些基本上都是預先訓練好的CNN模型來進行檢測。
def load_caffe_models(): age_net = cv2.dnn.readNetFromCaffe('deploy_age.prototxt', 'age_net.caffemodel') gender_net = cv2.dnn.readNetFromCaffe('deploy_gender.prototxt', 'gender_net.caffemodel') return(age_net, gender_net)
步驟7:如今咱們將執行人臉檢測、年齡檢測和性別檢測,併爲此在你的主函數內建立一個函數video_detector(age_net,gender_net),並將age_net和gender_net做爲其參數。
if __name__ == "__main__": age_net, gender_net = load_caffe_models() video_detector(age_net, gender_net)
步驟8:讀取步驟3中從VideoCapture()建立的cap對象。
cap.read()返回布爾值(True / False)。若是正確讀取框架,則它將爲True。
因此你能夠經過檢查這個返回值來檢查視頻的結尾。
有時,cap可能還沒有初始化捕獲。在這種狀況下,此代碼顯示錯誤。
你能夠經過cap.isOpened()方法檢查它是否已初始化. 若是是真的就繼續。不然,請使用cap.open()打開它.
ret, image = cap.read()
步驟9:將圖像轉換爲灰度圖像,由於OpenCV人臉檢測器須要灰度圖像。
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
步驟10:加載用於人臉檢測的預構建模型。
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
步驟11:如今,咱們如何使用級聯分類器從圖像中檢測人臉?
OpenCV的CascadedClassifier再次使其變得簡單,detectMultiScale()能夠準確地檢測你須要的內容。
detectMultiScale(image, scaleFactor, minNeighbors)
下面是應該傳遞給detectMultiScale()的參數。
這是一個檢測對象的通用函數,在這種狀況下,它將檢測人臉,由於咱們在人臉級聯中調用了此函數。若是找到一我的臉,則返回一個所述人臉的位置列表,格式爲「Rect(x,y,w,h)」,若是沒有,則返回「None」。
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
第12步:循環瀏覽人臉列表並在視頻中的人臉上繪製矩形。在這裏,咱們基本上是尋找面孔,分解面孔,它們的大小,並繪製矩形。
for (x, y, w, h )in faces: cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 0), 2) # Get Face face_img = image[y:y+h, h:h+w].copy()
步驟13:OpenCV提供了一個函數,能夠幫助對圖像進行預處理,以便進行深度學習分類:blobFromImage()。它執行:
平均減法
縮放比例
和可選的通道交換
因此blobFromImage4維的blob是從圖像建立的。可選地調整圖像大小並從中心裁剪圖像,減去平均值,按比例因子縮放值,交換藍色和紅色通道
blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size, mean, swapRB=True)
blob = cv2.dnn.blobFromImage(face_img, 1, (227, 227), MODEL_MEAN_VALUES, swapRB=False)
第14步:預測性別。
#Predict Gender gender_net.setInput(blob) gender_preds = gender_net.forward() gender = gender_list[gender_preds[0].argmax()]
第15步:預測年齡。
#Predict Age age_net.setInput(blob) age_preds = age_net.forward() age = age_list[age_preds[0].argmax()]
第16步:如今咱們必須使用openCV的put text()模塊將文本放到輸出框架上。
putText()的參數以下:
overlay_text = "%s %s" % (gender, age) cv2.putText(image, overlay_text, (x, y), font, 1, (255, 255, 255), 2, cv2.LINE_AA)
第17步:最後打印你的最終輸出。
cv2.imshow('frame', image)
最後咱們有:
if cv2.waitKey(1) & 0xFF == ord('q'): break
咱們的程序等待用戶按下一個鍵最多1毫秒。而後,它獲取讀取的鍵的值,並將其與0xFF
進行比較,0xFF
刪除底部8位以上的任何內容,並將結果與字母q的ASCII碼進行比較,這意味着用戶已決定經過按鍵盤上的q鍵退出。
輸出:視頻URL-1:https://www.youtube.com/watch...
視頻URL-2:https://www.youtube.com/watch...
頗有趣,不是嗎?但不太準確。
正如咱們在本文中看到的,在短短几行代碼中,咱們構建了年齡和性別檢測模型,從這裏開始,你還能夠將情感檢測和目標檢測合併到同一個模型中,並建立一個功能齊全的應用程序。
原文連接:https://towardsdatascience.co...
歡迎關注磐創AI博客站:
http://panchuang.net/
sklearn機器學習中文官方文檔:
http://sklearn123.com/
歡迎關注磐創博客資源彙總站:
http://docs.panchuang.net/