Python用dlib 识别了我手机里所有出现人脸的照片 (优点 准确度高 缺点速度慢,4500张图片 足足花了我3个半小时才识别玩 效果满意)

代码:

import cv2
import os
import dlib
'''
用dlib 识别 用opencv把手机拍的照片大小缩放 不是就不变  识别是否是图片格式 不是跳过
'''
# 读取函数,用来读取文件夹中的所有函数,输入参数是文件名
def read_directory(directory_name):
    for filename in os.listdir(directory_name):
        a= filename.split(".")[-1]
        if str(a) in ["JPG",'PNG','jpg','png']:
            # 用matplotlib的路径
            img1 = directory_name + "\\" + filename
            img3 = cv2.imread(img1)
            img2 = cv2.imread(img1)
            if img3.shape[0] >= int(2000): #现在手机像素高了 识别不了 还是图片缩小识别
                scale_percent = 25  # percent of original size   缩小到原来25%
                width = int(img3.shape[1] * scale_percent / 100)
                height = int(img3.shape[0] * scale_percent / 100)
                dim = (width, height)
                img = cv2.resize(img3, dim, interpolation=cv2.INTER_AREA)
            else:
                img = img3
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            # 人脸分类器
            detector = dlib.get_frontal_face_detector()
            # 获取人脸检测器
            predictor = dlib.shape_predictor(
                "shape_predictor_68_face_landmarks.dat"
            )
            dets = detector(gray, 1)
            if len(dets):  # 不为0则检测到人脸
                for face in dets:
                    shape = predictor(img, face)  # 寻找人脸的68个标定点
                    # 遍历所有点,打印出其坐标,并圈出来
                    for pt in shape.parts():
                        pt_pos = (pt.x, pt.y)
                        cv2.circle(img, pt_pos, 1, (0, 255, 0), 1)
                    b = filename.split(".")[-2]
                    cv2.imwrite(r"H:\renwu__opencv\%s.%s" % (b, a), img2)
                    # print(filename)
                    cv2.destroyAllWindows()
            else:
                print('没找到人脸!')
        else:
            print('跳过!')
read_directory(r'H:\renwu__opencv\zhaopian')#这里传入所要读取文件夹的绝对路径,加引号(引号不能省略!) 不要有中文

 

posted @ 2020-10-22 18:39  凹凸曼大人  阅读(313)  评论(0)    收藏  举报