python取得人臉的程式碼分享

小云云
發布: 2018-03-30 16:53:14
原創
1608 人瀏覽過

本文主要和大家分享python取得人臉的程式碼分享,希望大家根據本文能完成python取得人臉的功能。

usage:python   getface.py     src       out

# -*- codeing: utf-8 -*-
import sys
import os
import cv2
import dlib

input_dir = sys.argv[1]
output_dir = sys.argv[2]
print(input_dir)
print(output_dir)
size = 64

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()

index = 1
for (path, dirnames, filenames) in os.walk(input_dir):
    for filename in filenames:
        if filename.endswith('.jpg'):
            print('Being processed picture %s' % index)
        img_path = path + '/' + filename
        # 从文件读取图片
        img = cv2.imread(img_path)
        # 转为灰度图片
        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 使用detector进行人脸检测 dets为返回的结果
        dets = detector(gray_img, 1)

        # 使用enumerate 函数遍历序列中的元素以及它们的下标
        # 下标i即为人脸序号
        # left:人脸左边距离图片左边界的距离 ;right:人脸右边距离图片左边界的距离
        # top:人脸上边距离图片上边界的距离 ;bottom:人脸下边距离图片上边界的距离
        for i, d in enumerate(dets):
            x1 = d.top() if d.top() > 0 else 0
            y1 = d.bottom() if d.bottom() > 0 else 0
            x2 = d.left() if d.left() > 0 else 0
            y2 = d.right() if d.right() > 0 else 0
            # img[y:y+h,x:x+w]
            face = img[x1:y1, x2:y2]
            # 调整图片的尺寸
            face = cv2.resize(face, (size, size))
            #cv2.imshow('image', face)
            # 保存图片
            cv2.imwrite(output_dir + '/' + str(index) + '.jpg', face)
            index += 1

        key = cv2.waitKey(30) & 0xff
        if key == 27:
            sys.exit(0)  # -*- codeing: utf-8 -*-
登入後複製

相關建議:

#Python人臉辨識人臉辨識 -

#JavaScript人臉偵測的實作方法

python中使用OpenCV進行人臉偵測的範例#

以上是python取得人臉的程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!