有幾天沒有發文章了,我怕大家等急眼了,所以我先放出來一個代碼,這個代碼是基于dlib定位,然后基于深度學習的分類模型來對人臉進行分類的,一個分為五個類別【帥,一般,中等,丑,巨丑】,讓我們看看你的臉屬于那種型別吧,哈哈哈
這個代碼需要你有一個攝像頭,他是一個動態識別的程式,先上代碼,這個代碼要跑起來,要先下載我下面這個百度云鏈接里的東西:
鏈接:https://pan.baidu.com/s/1lcHfmxKGrafWczbpllVHQw
提取碼:qa6q
說明一下,一共三個檔案,其中dlib_video.py是運行程式,其它兩個是深度學習模型檔案和訓練好的權重檔案,放到和dlib_video.py同一目錄下就好了,不用管它,當然這個代碼要跑起來還需要pytorch和torchvision的環境,這個在我第一篇文章中就提供了安裝包,可以回看一下

展示一下主要的代碼
import cv2
import dlib
import torch
import PIL.Image as pimg
import torchvision.transforms as transforms
import time
import threading
test_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])])
def zmd_detect(image,train_img_size,model):
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
image = cv2.resize(image,(train_img_size[0], train_img_size[1]))
image = test_transform(image)
try:
image = image.view(1, 3, train_img_size[0], train_img_size[1]).to(device)
except:
image = image.view(1, 1, train_img_size[0], train_img_size[1]).to(device)
pre_prob = model(image)
pre_class = pre_prob.argmax(1).view(-1)
return pre_class.item()
def detect_face(detector,image,train_img_size,model):
try:
copy_image = image.copy()
locations = detector(image)
if len(locations) != 0:
for location in locations:
face_image = copy_image[location.top():location.bottom(),location.left():location.right()]
class_id = zmd_detect(face_image,train_img_size,model)
cv2.rectangle(image, (location.left(),location.top()), (location.right(),location.bottom()), (0, 255, 0), 2)
cv2.putText(image, class_name[class_id], (location.left(),location.top()), font, 1.2, (0, 0, 255), 2)
cv2.imshow("image", image)
else:
cv2.imshow("image", image)
k = cv2.waitKey(1)
except:
cv2.imshow("image", image)
k = cv2.waitKey(1)
if __name__ == '__main__':
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model_path = './best.pth'
model = torch.load(model_path).to(device)
model.eval()
train_img_size = [96,96]
class_name = ["handsome","commonly","secondary","ugly","giant ugly"]
# 定義定位人臉的定位器
detector = dlib.get_frontal_face_detector()
font = cv2.FONT_HERSHEY_SIMPLEX
# 獲取攝像頭
capture = cv2.VideoCapture(0)
while capture.isOpened():
# 攝像頭打開,讀取影像
flag, image = capture.read()
# 定位+識別 人臉
image = detect_face(detector,image,train_img_size,model)
k = cv2.waitKey(1)
# 釋放攝像頭
capture.release()
# 關閉所有視窗
cv2.destroyAllWindows()
演示視頻,博主本主出鏡了,哈哈
video
最后,上周獲得了一個88名,不錯不錯,繼續努力

下一篇文章我們直接開說深度學習的模型怎么訓練出來的,就是上面那個best.pth怎么訓練出來的
至此,敬禮,salute!!!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/293704.html
標籤:AI
上一篇:【卷積神經網路】經典分類網路結構
