python3调用虹软3.0人脸识别

平台 windows,linux没试过应该也可以只需将虹软sdk换成linux版本即可。
软件依赖 cv2、flask、虹软sdk3版本(2版本的也可以)
main_flask是以图片的方式在浏览器上实时浏览,
main_client是一个窗口的形式展现实时监测视频数据。


image.png

虹软的sdk怎么搞就不多说了,自己看官网。
具体代码如下:

  1. flask程序主入口 main_flask.py
import face_dll
import face_class
from ctypes import *
import cv2
import face_function as fun
import face_feature_extract
import video_camera
from flask import Flask, abort, request, jsonify, Response

app = Flask(__name__)

Appkey = b''
SDKey = b''

'''
存放人脸库的信息,key为对应的图片名即为1.jpg或者2.jpg
'''
faceInfos = {'1':{'name':'Ju Jingyi','gender':'girl','age':'25','image':'images/1.jpg'},'2':{'name':'Ju Jingyi','gender':'girl','age':'25','image':'images/2.jpg'}}


'''
激活sdk,激活一次即可
'''


def active():
    ret = fun.active(Appkey, SDKey)
    if ret == 0 or ret == 90114:
        print('激活成功:', ret)
    else:
        print('激活失败:', ret)
        pass


def init():
    # 初始化 1 视频(0x00000000)或图片(0xFFFFFFFF)模式,
    ret = fun.init(0x00000000)
    if ret[0] == 0:
        print('初始化成功:', ret, '句柄', fun.Handle)
    else:
        print('初始化失败:', ret)

def gen():
    
    videoCamera = video_camera.VideoCamera(faceFeatures, faceInfos)

    while True:
        ret, frame = videoCamera.get_frame()

        if ret:
            yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame.tobytes() + b'\r\n\r\n')
            
'''
返回图片流
'''
@app.route('/video_feed/')
def video_feed():
    return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == "__main__":
    #active()
    # 加载人脸资源
    faceFeatures = face_feature_extract.load_face_feature(faceInfos)
    init()
    app.run(host="0.0.0.0", port=8080, debug=True, threaded=True, processes=True)
  1. 摄像头类 video_camera.py
import cv2
import face_function as fun
import face_feature_extract
import face_class

'''
摄像头类
'''


class VideoCamera(object):
    def __init__(self, faceFeatures, faceInfos):
        # 通过opencv获取实时视频流
        self.videoCapture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
        self.frame_width = int(self.videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.frame_height = int(
            self.videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        self.faceFeatures = faceFeatures
        self.faceInfos = faceInfos

    def __del__(self):
        self.videoCapture.release()

    '''
    将视频帧转换为字节流返回
    '''

    def get_frame(self):
        ret, frame = self.videoCapture.read()
        if ret:
            # 加载图片
            imageData = face_class.ImageData(
                frame, self.frame_width, self.frame_height)
            ret, faces = fun.detectFaces(fun.deal_image_data(imageData))
            if ret == 0:
                frame = fun.deal_frame(
                    imageData, faces, self.faceFeatures, self.faceInfos)
            img_fps = 80
            img_param = [int(cv2.IMWRITE_JPEG_QUALITY), img_fps]
            # 转化
            ret, frame = cv2.imencode('.jpg', frame, img_param)
        return ret, frame

3.人脸识别相关函数 face_function.py

import face_dll
import face_class
from ctypes import *
import cv2
from io import BytesIO

# from Main import *
Handle = c_void_p()
c_ubyte_p = POINTER(c_ubyte)

# 激活函数


def active(appkey, sdkey):
    ret = face_dll.active(appkey, sdkey)
    return ret

# 初始化函数


def init(model):
    '''
        1 视频(0x00000000)或图片(0xFFFFFFFF)模式,
        2 角度(),
        3 识别的最小人脸比例 = 图片长边 / 人脸框长边的比值 默认推荐值:VIDEO模式推荐16;IMAGE模式推荐32
        4 最大需要检测的人脸个数,取值范围[1,50],
        5 需要启用的功能组合,可多选ASF_FACE_DETECT 0x00000001 //人脸检测 SF_FACERECOGNITION 0x00000004 //人脸特征 ASF_AGE 0x00000008 //年龄 ASF_GENDER 0x00000010 //性别
        ASF_FACE3DANGLE 0x00000020 //3D角度 ASF_LIVENESS 0x00000080 //RGB活体 ASF_IR_LIVENESS 0x00000400 //IR活体 这些属性均是以常量值进行定义,可通过 | 位运算符进行组合使用。
        例如 MInt32 combinedMask = ASF_FACE_DETECT | ASF_FACERECOGNITION | ASF_LIVENESS;
        6 返回激活句柄
    '''
    ret = face_dll.initEngine(model, 0x1, 16, 10, 5, byref(Handle))
    return ret, Handle

# cv2记载图片并处理


def LoadImg(imageData):

    img = cv2.imread(imageData.filepath)
    sp = img.shape

    img = cv2.resize(img, (sp[1]//4*4, sp[0]//4*4))
    sp = img.shape

    imageData.image = img
    imageData.width = sp[1]
    imageData.height = sp[0]

    return imageData


'''
处理图片改变大小
'''


def deal_image_data(imageData):

    shape = imageData.image.shape

    image = cv2.resize(imageData.image, (shape[1]//4*4, shape[0]//4*4))
    shape = image.shape

    imageData.image = image
    imageData.width = shape[1]
    imageData.height = shape[0]

    return imageData


def detectFaces(imageData):
    faces = face_class.ASF_MultiFaceInfo()
    imgby = bytes(imageData.image)
    imgcuby = cast(imgby, c_ubyte_p)
    ret = face_dll.detectFaces(
        Handle, imageData.width, imageData.height, 0x201, imgcuby, byref(faces))
    return ret, faces

# 显示人脸识别图片


def showimg(im, faces):
    for i in range(0, faces.faceNum):
        ra = faces.faceRect[i]
        cv2.rectangle(im.image, (ra.left, ra.top),
                      (ra.right, ra.bottom), (255, 0, 0,), 2)

    cv2.imshow('faces', im.image)
    cv2.waitKey(0)

# 显示人脸识别图片


def showimg2(imageData, faces, faceFeatures, faceInfos):

    for i in range(0, faces.faceNum):
        # 画出人脸框
        ra = faces.faceRect[i]
        cv2.rectangle(imageData.image, (ra.left, ra.top),
                      (ra.right, ra.bottom), (255, 0, 0,), 2)

        peopleName = 'unknown'
        res = 0.5

        # 提取单人1特征
        ft = getsingleface(faces, i)
        ret, faceFeature = faceFeatureExtract(imageData, ft)

        if ret == 0:
            for item in faceFeatures:
                ret, result = faceFeatureCompare(
                    faceFeature, item['faceFeature'])
                if ret == 0:
                    if result > res:
                        res = result
                        peopleName = faceInfos[item['id']]['name']

        cv2.putText(imageData.image, peopleName, (ra.left, ra.top - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0,), 1, cv2.LINE_AA)

    cv2.imshow('faces', imageData.image)


def deal_frame(imageData, faces, faceFeatures, faceInfos):

    for i in range(0, faces.faceNum):
        # 画出人脸框
        ra = faces.faceRect[i]
        cv2.rectangle(imageData.image, (ra.left, ra.top),
                      (ra.right, ra.bottom), (255, 0, 0,), 2)

        peopleName = 'unknown'
        res = 0.5

        # 提取单人1特征
        ft = getsingleface(faces, i)
        ret, faceFeature = faceFeatureExtract(imageData, ft)

        if ret == 0:
            for item in faceFeatures:
                ret, result = faceFeatureCompare(
                    faceFeature, item['faceFeature'])
                if ret == 0:
                    if result > res:
                        res = result
                        peopleName = faceInfos[item['id']]['name']

        cv2.putText(imageData.image, peopleName, (ra.left, ra.top - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0,), 1, cv2.LINE_AA)

    return imageData.image
# 提取人脸特征


def faceFeatureExtract(im, ft):
    detectedFaces = face_class.ASF_FaceFeature()
    img = im.image
    imgby = bytes(im.image)
    imgcuby = cast(imgby, c_ubyte_p)

    ret = face_dll.faceFeatureExtract(
        Handle, im.width, im.height, 0x201, imgcuby, ft, byref(detectedFaces))
    if ret == 0:
        retz = face_class.ASF_FaceFeature()
        retz.featureSize = detectedFaces.featureSize
        # 必须操作内存来保留特征值,因为c++会在过程结束后自动释放内存
        retz.feature = face_dll.malloc(detectedFaces.featureSize)
        face_dll.memcpy(retz.feature, detectedFaces.feature,
                        detectedFaces.featureSize)
        return ret, retz
    else:
        return ret, None

# 特征值比对,返回比对结果


def faceFeatureCompare(faceFeature1, FaceFeature2):
    result = c_float()
    ret = face_dll.faceFeatureCompare(
        Handle, faceFeature1, FaceFeature2, byref(result))
    return ret, result.value

# 单人特征写入文件


def writeFTFile(feature, filepath):
    f = BytesIO(string_at(feature.feature, feature.featureSize))
    a = open(filepath, 'wb')
    a.write(f.getvalue())
    a.close()

# 从多人中提取单人数据


def getsingleface(singleface, index):

    ft = face_class.ASF_SingleFaceInfo()
    ra = singleface.faceRect[index]
    ft.faceRect.left = ra.left
    ft.faceRect.right = ra.right
    ft.faceRect.top = ra.top
    ft.faceRect.bottom = ra.bottom
    ft.faceOrient = singleface.faceOrient[index]

    return ft

# 从文件获取特征值


def ftfromfile(filepath):
    fas = face_class.ASF_FaceFeature()
    f = open(filepath, 'rb')
    b = f.read()
    f.close()
    fas.featureSize = b.__len__()
    fas.feature = face_dll.malloc(fas.featureSize)
    face_dll.memcpy(fas.feature, b, fas.featureSize)
    return fas

4.人脸特征值提取face_feature_extract.py

import face_dll
import face_class
import cv2
import face_function as fun
import os
from ctypes import string_at

'''
存放人脸特征值的集合
'''
faceFeatures = []


'''
初始化sdk设置为图片模式以加载更为精确的特征值集合
'''


def init():
    # 初始化
    ret = fun.init(0xFFFFFFFF)
    if ret[0] == 0:
        print('初始化成功:', ret, '句柄', fun.Handle)
    else:
        print('初始化失败:', ret)


'''
提取图片文件里面的人脸特征值
'''


def face_feature_extract(filepath):

    imageData = face_class.ImageLoadData(filepath)
    imageData = fun.LoadImg(imageData)
    ret, faces = fun.detectFaces(imageData)

    if ret == 0:
        # 提取单人1特征
        ft = fun.getsingleface(faces, 0)
        ret, faceFeature = fun.faceFeatureExtract(imageData, ft)

    return ret, faceFeature


'''
读取人脸资源库所有的图片
'''


def read_images(filePath):
    for i, j, files in os.walk(filePath):
        return files


def load_face_feature(faceInfos):
    init()

    for info in faceInfos:
        imagePath = faceInfos[info]['image']
        if imagePath.find('.jpg'):
            ret, faceFeature = face_feature_extract(imagePath)
            if ret == 0:
                print("add faceFeature", info)
                faceFeatures.append({'id': info, 'faceFeature': faceFeature})

    return faceFeatures


if __name__ == "__main__":
    faceInfos = {'1':{'name':'Ju Jingyi','gender':'girl','age':'25','image':'images/1.jpg'},'2':{'name':'Ju Jingyi','gender':'girl','age':'25','image':'images/2.jpg'}}
    load_face_feature(faceInfos)

5.特征值对比 face_feature_compare.py

import face_dll
import face_class
import face_function as fun
import face_feature_extract

'''
本地图片提取的特征值与内存的特征值对比
'''


def face_feature_compare(faceFeature):

    # 结果比对
    faceFeatures = face_feature_extract.loadFaceFeature('images/')

    for item in faceFeatures:

        ret, result = fun.faceFeatureCompare(faceFeature, item['faceFeature'])
        if ret == 0:
            print('name %s similarity %s' % (item['name'], result))


if __name__ == "__main__":
    ret, faceFeature = face_feature_extract.faceFeatureExtract(
        'images/JuJingyi.jpg')

    if ret == 0:
        face_feature_compare(faceFeature)

6.c++中的结构体python封装 face_class.py

from ctypes import c_int32, c_char_p, Structure, POINTER, c_void_p, c_float, c_int8, c_uint32

# 人脸框
'''
MRECT* faceRect 人脸框数组
MInt32* faceOrient 人脸角度数组
MInt32 faceNum 检测到的人脸数
MInt32* faceID 一张人脸从进入画面直到离开画面,faceID不变。
在VIDEO模式下有效,IMAGE模式下为空

'''

class MRECT(Structure):
    _fields_ = [(u'left', c_int32), (u'top', c_int32),
                (u'right', c_int32), (u'bottom', c_int32)]

# 版本信息     版本号,构建日期,版权说明
'''
MPChar Version 版本号
MPChar BuildDate 构建日期
MPChar CopyRight 版权说明
'''

class ASF_VERSION(Structure):
    _fields_ = [('Version', c_char_p), ('BuildDate',
                                        c_char_p), ('CopyRight', c_char_p)]

# 单人人脸信息  人脸狂,人脸角度
'''
MRECT faceRect 人脸框
MInt32 faceOrient 人脸角度
'''

class ASF_SingleFaceInfo(Structure):
    _fields_ = [('faceRect', MRECT), ('faceOrient', c_int32)]

# 多人人脸信息 人脸框数组,人脸角度数组,人脸数
'''
MRECT* faceRect 人脸框数组
MInt32* faceOrient 人脸角度数组
MInt32 faceNum 检测到的人脸数
MInt32* faceID 一张人脸从进入画面直到离开画面,faceID不变。在VIDEO模式下有效,IMAGE模式下为空
'''

class ASF_MultiFaceInfo(Structure):
    _fields_ = [(u'faceRect', POINTER(MRECT)), (u'faceOrient',
                                                POINTER(c_int32)), (u'faceNum', c_int32)]

# 人脸特征 人脸特征,人脸特征长度
'''
MByte* feature 人脸特征
MInt32 featureSize 人脸特征长度
'''

class ASF_FaceFeature(Structure):
    _fields_ = [('feature', c_void_p), ('featureSize', c_int32)]

# 自定义图片类


class ImageData:
    def __init__(self, image, width, height):
        self.image = image
        self.width = width
        self.height = height

# 自定义图片类


class ImageLoadData:
    def __init__(self, filepath):
        self.filepath = filepath
        self.image = None
        self.width = 0
        self.height = 0

#年龄信息
'''
MInt32* ageArray 0:未知; >0:年龄
MInt32 num 检测的人脸数
'''
class ASF_AgeInfo(Structure):
    _fields_ = [('ageArray', POINTER(c_int32)), ('num', c_int32)]

#性别信息
'''
MInt32* genderArray 0:男性; 1:女性; -1:未知
MInt32 num 检测的人脸数
'''
class ASF_GenderInfo(Structure):
    _fields_ = [('genderArray', POINTER(c_int32)), ('num', c_int32)]

#3D角度信息
'''
MFloat* roll 横滚角
MFloat* yaw 偏航角
MFloat* pitch 俯仰角
MInt32* status 0:正常; 非0:异常
MInt32 num 检测的人脸个数
'''
class ASF_Face3DAngle(Structure):
    _fields_ = [('roll', POINTER(c_float)), ('yaw', POINTER(c_float)), ('pitch', POINTER(c_float)), ('status', POINTER(c_int32)), ('num', c_int32)]

#活体置信度
'''
MFloat thresholdmodel_BGR BGR活体检测阈值设置,默认值0.5
MFloat thresholdmodel_IR IR活体检测阈值设置,默认值0.7
'''
class ASF_LivenessThreshold(Structure):
    _fields_ = [('thresholdmodel_BGR', c_float), ('thresholdmodel_IR', c_float)]

#活体信息
'''
MInt32* isLive 0:非真人; 1:真人;-1:不确定; -2:传入人脸数 > 1;-3: 人脸过小;-4: 角度过大;-5: 人脸超出边界
MInt32 num 检测的人脸个数
'''
class ASF_LivenessInfo(Structure):
    _fields_ = [('isLive', POINTER(c_int32)), ('num', c_int32)]

#图像数据信息,该结构体在 asvloffscreen. 基础的头文件中
'''
MUInt32 u32PixelArrayFormat 颜色格式
MInt32 i32Width 图像宽度
MInt32 i32Height 图像高度
MUInt8** ppu8Plane 图像数据
MInt32* pi32Pitch 图像步长
'''
class ASVLOFFSCREEN(Structure):
    _fields_ = [('u32PixelArrayFormat', c_uint32), ('i32Width', c_int32), ('i32Height', c_int32), ('ppu8Plane', POINTER(POINTER(c_int32))), ('pi32Pitch', POINTER(c_int32))]

  1. sdk库pyhton接口封装 face_dll.py
from ctypes import c_int32, c_char_p, c_void_p, c_float, c_size_t, c_ubyte, c_long, cdll, POINTER, CDLL
from face_class import *

wuyongdll = CDLL('libarcsoft/libarcsoft_face.dll')
dll = CDLL('libarcsoft/libarcsoft_face_engine.dll')
dllc = cdll.msvcrt
ASF_DETECT_MODE_VIDEO = 0x00000000
ASF_DETECT_MODE_IMAGE = 0xFFFFFFFF
c_ubyte_p = POINTER(c_ubyte)

# 激活
active = dll.ASFActivation
active.restype = c_int32
active.argtypes = (c_char_p, c_char_p)

# 初始化
initEngine = dll.ASFInitEngine
initEngine.restype = c_int32
initEngine.argtypes = (c_long, c_int32, c_int32,
                       c_int32, c_int32, POINTER(c_void_p))

# 人脸识别
detectFaces = dll.ASFDetectFaces
detectFaces.restype = c_int32
detectFaces.argtypes = (c_void_p, c_int32, c_int32,
                        c_int32, POINTER(c_ubyte), POINTER(ASF_MultiFaceInfo))

# 特征提取
faceFeatureExtract = dll.ASFFaceFeatureExtract
faceFeatureExtract.restype = c_int32
faceFeatureExtract.argtypes = (c_void_p, c_int32, c_int32, c_int32, POINTER(
    c_ubyte), POINTER(ASF_SingleFaceInfo), POINTER(ASF_FaceFeature))

# 特征比对
faceFeatureCompare = dll.ASFFaceFeatureCompare
faceFeatureCompare.restype = c_int32
faceFeatureCompare.argtypes = (c_void_p, POINTER(
    ASF_FaceFeature), POINTER(ASF_FaceFeature), POINTER(c_float))
malloc = dllc.malloc
free = dllc.free
memcpy = dllc.memcpy

malloc.restype = c_void_p
malloc.argtypes = (c_size_t, )
free.restype = None
free.argtypes = (c_void_p, )
memcpy.restype = c_void_p
memcpy.argtypes = (c_void_p, c_void_p, c_size_t)

#ASFFaceFeatureExtractEx第二次特征提取
'''
hEngine in 引擎句柄
imgData in 图像数据
faceInfo in 单人脸信息(人脸框、人脸角度)
feature out 提取到的人脸特征信息
'''
faceFeatureExtractEx = dll.ASFFaceFeatureExtractEx
faceFeatureExtractEx.restype = c_int32
faceFeatureExtractEx.argtypes = (c_void_p, POINTER(ASVLOFFSCREEN), POINTER(ASF_SingleFaceInfo), POINTER(ASF_FaceFeature))

#设置RGB/IR活体阈值,若不设置内部默认RGB:0.5 IR:0.7
'''
hEngine in 引擎句柄
threshold in 活体阈值,推荐RGB:0.5 IR:0.7
'''
setLivenessParam = dll.ASFSetLivenessParam
setLivenessParam.restype = c_int32
setLivenessParam.argtypes = (c_void_p, ASF_LivenessThreshold)

#人脸属性检测(年龄/性别/人脸3D角度),最多支持4张人脸信息检测,超过部分返回未知(活体仅支持单张人脸检测,超出返回未知),接口不支持IR图像检测
'''
hEngine in 引擎句柄

width in 图片宽度,为4的倍数

height in 图片高度,YUYV/I420/NV21/NV12格式为2的倍数;BGR24格式无限制;

format in 支持YUYV/I420/NV21/NV12/BGR24
ASVL_PAF_NV21 2050 8-bit Y 通道,8-bit 2x2 采样 V 与 U 分量交织通道
ASVL_PAF_NV12 2049 8-bit Y 通道,8-bit 2x2 采样 U 与 V 分量交织通道
ASVL_PAF_RGB24_B8G8R8 513 RGB 分量交织,按 B, G, R, B 字节序排布
ASVL_PAF_I420 1537 8-bit Y 通道, 8-bit 2x2 采样 U 通道, 8-bit 2x2 采样 V通道
ASVL_PAF_YUYV 1289 YUV 分量交织, V 与 U 分量 2x1 采样,按 Y0, U0, Y1,V0 字节序排布
ASVL_PAF_GRAY 1793 8-bit IR图像
ASVL_PAF_DEPTH_U16 3074 16-bit IR图像

imgData in 图像数据

detectedFaces in 多人脸信息

combinedMask in 1.检测的属性(ASF_AGE、ASF_GENDER、 ASF_FACE3DANGLE、ASF_LIVENESS),支持多选 2.检测的属性须在引擎初始化接口的combinedMask参数中启用
#define ASF_FACE_DETECT 0x00000001 //人脸检测
#define ASF_FACERECOGNITION 0x00000004 //人脸特征
#define ASF_AGE 0x00000008 //年龄
#define ASF_GENDER 0x00000010 //性别
#define ASF_FACE3DANGLE 0x00000020 //3D角度
#define ASF_LIVENESS 0x00000080 //RGB活体
#define ASF_IR_LIVENESS 0x00000400 //IR活体
多组合 MInt32 processMask = ASF_AGE | ASF_GENDER | ASF_FACE3DANGLE | ASF_LIVENESS;
'''
ASVL_PAF_RGB24_B8G8R8 = 513
process = dll.ASFProcess
process.restype = c_int32
process.argtypes = (c_void_p, c_int32, c_int32, c_int32, POINTER(c_ubyte), ASF_MultiFaceInfo, c_int32)

#人脸信息检测(年龄/性别/人脸3D角度),最多支持4张人脸信息检测,超过部分返回未知(活体仅支持单张人脸检测,超出返回未知),接口不支持IR图像检测。
'''
hEngine in 引擎句柄
imgData in 图像数据
detectedFaces in 多人脸信息
combinedMask in
    1.检测的属性(ASF_AGE、ASF_GENDER、 ASF_FACE3DANGLE、ASF_LIVENESS),支持多选
    2.检测的属性须在引擎初始化接口的combinedMask参数中启用
'''
processEx = dll.ASFProcessEx
processEx.restype = c_int32
processEx.argtypes = (c_void_p, POINTER(c_ubyte), ASF_MultiFaceInfo, c_int32)

#ASFGetAge 获取年龄信息。
'''
hEngine in 引擎句柄
ageInfo out 检测到的年龄信息数组
'''
getAge = dll.ASFGetAge
getAge.restype = c_int32
getAge.argtypes = (c_void_p, ASF_AgeInfo)

#ASFGetGender 获取性别信息。
'''
hEngine in 引擎句柄
genderInfo out 检测到的性别信息数组
'''
getGender = dll.ASFGetGender
getGender.restype = c_int32
getGender.argtypes = (c_void_p, ASF_GenderInfo)

#ASFGetFace3DAngle 获取3D角度信息。
'''
hEngine in 引擎句柄
p3DAngleInfo out 检测到的3D角度信息数组
'''
getFace3DAngle = dll.ASFGetFace3DAngle
getFace3DAngle.restype = c_int32
getFace3DAngle.argtypes = (c_void_p, ASF_Face3DAngle)

#ASFGetLivenessScore 获取RGB活体信息。
'''
hEngine in 引擎句柄
livenessInfo out 检测到的活体信息
'''
getLivenessScore = dll.ASFGetLivenessScore
getLivenessScore.restype = c_int32
getLivenessScore.argtypes = (c_void_p, ASF_LivenessInfo)

#ASFProcess_IR 该接口仅支持单人脸 IR 活体检测,超出返回未知
'''
hEngine in 引擎句柄
width in 图片宽度,为4的倍数
height in 图片高度
format in 图像颜色格式
imgData in 图像数据
detectedFaces in 多人脸信息
combinedMask in 目前仅支持 ASF_IR_LIVENESS(0x00000400)
'''
process_IR = dll.ASFProcess_IR
process_IR.restype = c_int32
process_IR.argtypes = (c_void_p, c_int32, c_int32, c_int32, POINTER(c_ubyte), ASF_MultiFaceInfo, c_int32)

#ASFProcessEx_IR 该接口仅支持单人脸 IR 活体检测,超出返回未知
'''
hEngine in 引擎句柄
imgData in 图像数据
detectedFaces in 多人脸信息
combinedMask in 目前仅支持 ASF_IR_LIVENESS
'''
processEx_IR = dll.ASFProcessEx_IR
processEx_IR.restype = c_int32
processEx_IR.argtypes = (c_void_p, POINTER(c_ubyte), ASF_MultiFaceInfo, c_int32)

#ASFGetLivenessScore_IR 获取IR活体信息。
'''
hEngine in 引擎句柄
livenessInfo out 检测到的IR活体信息
'''
getLivenessScore_IR = dll.ASFGetLivenessScore_IR
getLivenessScore_IR.restype = c_int32
getLivenessScore_IR.argtypes = (c_void_p, POINTER(c_ubyte), ASF_LivenessInfo)

#ASFGetVersion 获取SDK版本信息。
'''
'''
getVersion = dll.ASFGetVersion
getVersion.restype = ASF_VERSION

#ASFUninitEngine 销毁SDK引擎。
'''
hEngine in 引擎句柄
'''
uninitEngine = dll.ASFUninitEngine
uninitEngine.restype = c_int32
uninitEngine.argtypes = (c_void_p,)

8.窗口的形式展现 main_client.py

import face_dll
import face_class
from ctypes import *
import cv2
import face_function as fun
import face_feature_extract

Appkey = b''
SDKey = b''

'''
存放人脸库的信息,key为对应的图片名即为1.jpg或者2.jpg
'''
faceInfos = {'1':{'name':'Ju Jingyi','gender':'girl','age':'25','image':'images/1.jpg'},'2':{'name':'Ju Jingyi','gender':'girl','age':'25','image':'images/2.jpg'}}


'''
激活sdk,激活一次即可
'''


def active():
    ret = fun.active(Appkey, SDKey)
    if ret == 0 or ret == 90114:
        print('激活成功:', ret)
    else:
        print('激活失败:', ret)
        pass


def init():
    # 初始化 1 视频(0x00000000)或图片(0xFFFFFFFF)模式,
    ret = fun.init(0x00000000)
    if ret[0] == 0:
        print('初始化成功:', ret, '句柄', fun.Handle)
    else:
        print('初始化失败:', ret)


def start(faceFeatures):
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    while True:
        # get a frame
        ret, frame = cap.read()
        if ret:
            # 加载图片
            imageData = face_class.ImageData(frame, frame_width, frame_height)
            ret, faces = fun.detectFaces(fun.deal_image_data(imageData))
            if ret == 0:
                fun.showimg2(imageData, faces, faceFeatures, faceInfos)
            else:
                pass

        # show a frame
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    #active()
    # 加载人脸资源
    faceFeatures = face_feature_extract.load_face_feature(faceInfos)
    init()
    start(faceFeatures)

项目地址:码云

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350