日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python dlib学习(九):人脸聚类

發布時間:2025/3/21 python 56 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python dlib学习(九):人脸聚类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

前面的博客介紹過使用dlib進行人臉檢測、比對、檢測特征點等等操作。
python dlib學習(一):人臉檢測
python dlib學習(二):人臉特征點標定
python dlib學習(五):比對人臉
這次再將那些操作綜合一下,進行人臉聚類。識別圖片中的人臉,并分類。這里使用的是聚類,屬于無監督學習。這里對每個人臉的區分與比對人臉中原理相同,將人臉映射到128D的空間中,計算彼此之間的距離。距離近的視作一個人,距離遠的視作不是一個人,而判定的標準閾值由自己選定,通常是0.6。

目錄結構

  • faces文件夾保存測試圖片;
  • model文件夾保存模型文件,也可以自己訓練,我偷懶使用了官方提供的;
  • output文件夾中存放輸出結果;
  • 源碼直接放在根目錄。

程序

# coding: utf-8 """ @author: xhb """import sys import os import dlib import glob import cv2# 指定路徑 current_path = os.getcwd() model_path = current_path + '/model/' shape_predictor_model = model_path + '/shape_predictor_5_face_landmarks.dat' face_rec_model = model_path + '/dlib_face_recognition_resnet_model_v1.dat' face_folder = current_path + '/faces/' output_folder = current_path + '/output/'# 導入模型 detector = dlib.get_frontal_face_detector() shape_detector = dlib.shape_predictor(shape_predictor_model) face_recognizer = dlib.face_recognition_model_v1(face_rec_model)# 為后面操作方便,建了幾個列表 descriptors = [] images = [] # 遍歷faces文件夾中所有的圖片 for f in glob.glob(os.path.join(face_folder, "*.jpg")):print('Processing file:{}'.format(f))# 讀取圖片img = cv2.imread(f)# 轉換到rgb顏色空間img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# 檢測人臉dets = detector(img2, 1)print("Number of faces detected: {}".format(len(dets)))# 遍歷所有的人臉for index, face in enumerate(dets):# 檢測人臉特征點shape = shape_detector(img2, face)# 投影到128Dface_descriptor = face_recognizer.compute_face_descriptor(img2, shape)# 保存相關信息descriptors.append(face_descriptor)images.append((img2, shape))# 聚類 labels = dlib.chinese_whispers_clustering(descriptors, 0.5) print("labels: {}".format(labels)) num_classes = len(set(labels)) print("Number of clusters: {}".format(num_classes))# 為了方便操作,用字典類型保存 face_dict = {} for i in range(num_classes):face_dict[i] = [] # print face_dict for i in range(len(labels)):face_dict[labels[i]].append(images[i])# print face_dict.keys() # 遍歷字典,保存結果 for key in face_dict.keys():file_dir = os.path.join(output_folder, str(key))if not os.path.isdir(file_dir):os.makedirs(file_dir)for index, (image, shape) in enumerate(face_dict[key]):file_path = os.path.join(file_dir, 'face_' + str(index))print file_pathdlib.save_face_chip(image, shape, file_path, size=150, padding=0.25)

程序很簡單,不做贅述。

結果




后記

dlib作為開源庫,為我們提供了很方便的api工具,可以實現許多很酷的功能。當然那些功能也可以自己實現。不管怎樣,都很有趣吧!

總結

以上是生活随笔為你收集整理的python dlib学习(九):人脸聚类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。