python3調(diào)用虹軟3.0人臉識別

平臺 windows,linux沒試過應(yīng)該也可以只需將虹軟sdk換成linux版本即可锋恬。
軟件依賴 cv2搪花、flask盯桦、虹軟sdk3版本(2版本的也可以)
main_flask是以圖片的方式在瀏覽器上實時瀏覽拆内,
main_client是一個窗口的形式展現(xiàn)實時監(jiān)測視頻數(shù)據(jù)连锯。


image.png

虹軟的sdk怎么搞就不多說了归苍,自己看官網(wǎng)。
具體代碼如下:

  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為對應(yīng)的圖片名即為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()

    '''
    將視頻幀轉(zhuǎn)換為字節(jié)流返回
    '''

    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]
            # 轉(zhuǎn)化
            ret, frame = cv2.imencode('.jpg', frame, img_param)
        return ret, frame

3.人臉識別相關(guān)函數(shù) 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)

# 激活函數(shù)


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

# 初始化函數(shù)


def init(model):
    '''
        1 視頻(0x00000000)或圖片(0xFFFFFFFF)模式,
        2 角度(),
        3 識別的最小人臉比例 = 圖片長邊 / 人臉框長邊的比值 默認(rèn)推薦值:VIDEO模式推薦16运怖;IMAGE模式推薦32
        4 最大需要檢測的人臉個數(shù)拼弃,取值范圍[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活體 這些屬性均是以常量值進(jìn)行定義驳规,可通過 | 位運(yùn)算符進(jìn)行組合使用肴敛。
        例如 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
        # 必須操作內(nèi)存來保留特征值,因為c++會在過程結(jié)束后自動釋放內(nèi)存
        retz.feature = face_dll.malloc(detectedFaces.featureSize)
        face_dll.memcpy(retz.feature, detectedFaces.feature,
                        detectedFaces.featureSize)
        return ret, retz
    else:
        return ret, None

# 特征值比對,返回比對結(jié)果


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()

# 從多人中提取單人數(shù)據(jù)


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設(shè)置為圖片模式以加載更為精確的特征值集合
'''


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

'''
本地圖片提取的特征值與內(nèi)存的特征值對比
'''


def face_feature_compare(faceFeature):

    # 結(jié)果比對
    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++中的結(jié)構(gòu)體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 人臉框數(shù)組
MInt32* faceOrient 人臉角度數(shù)組
MInt32 faceNum 檢測到的人臉數(shù)
MInt32* faceID 一張人臉從進(jìn)入畫面直到離開畫面署海,faceID不變吗购。
在VIDEO模式下有效,IMAGE模式下為空

'''

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

# 版本信息     版本號,構(gòu)建日期,版權(quán)說明
'''
MPChar Version 版本號
MPChar BuildDate 構(gòu)建日期
MPChar CopyRight 版權(quán)說明
'''

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)]

# 多人人臉信息 人臉框數(shù)組,人臉角度數(shù)組,人臉數(shù)
'''
MRECT* faceRect 人臉框數(shù)組
MInt32* faceOrient 人臉角度數(shù)組
MInt32 faceNum 檢測到的人臉數(shù)
MInt32* faceID 一張人臉從進(jìn)入畫面直到離開畫面砸狞,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 檢測的人臉數(shù)
'''
class ASF_AgeInfo(Structure):
    _fields_ = [('ageArray', POINTER(c_int32)), ('num', c_int32)]

#性別信息
'''
MInt32* genderArray 0:男性; 1:女性; -1:未知
MInt32 num 檢測的人臉數(shù)
'''
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 檢測的人臉個數(shù)
'''
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活體檢測閾值設(shè)置刀森,默認(rèn)值0.5
MFloat thresholdmodel_IR IR活體檢測閾值設(shè)置踱启,默認(rèn)值0.7
'''
class ASF_LivenessThreshold(Structure):
    _fields_ = [('thresholdmodel_BGR', c_float), ('thresholdmodel_IR', c_float)]

#活體信息
'''
MInt32* isLive 0:非真人; 1:真人研底;-1:不確定埠偿; -2:傳入人臉數(shù) > 1;-3: 人臉過邪窕蕖冠蒋;-4: 角度過大;-5: 人臉超出邊界
MInt32 num 檢測的人臉個數(shù)
'''
class ASF_LivenessInfo(Structure):
    _fields_ = [('isLive', POINTER(c_int32)), ('num', c_int32)]

#圖像數(shù)據(jù)信息乾胶,該結(jié)構(gòu)體在 asvloffscreen. 基礎(chǔ)的頭文件中
'''
MUInt32 u32PixelArrayFormat 顏色格式
MInt32 i32Width 圖像寬度
MInt32 i32Height 圖像高度
MUInt8** ppu8Plane 圖像數(shù)據(jù)
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 圖像數(shù)據(jù)
faceInfo in 單人臉信息(人臉框抖剿、人臉角度)
feature out 提取到的人臉特征信息
'''
faceFeatureExtractEx = dll.ASFFaceFeatureExtractEx
faceFeatureExtractEx.restype = c_int32
faceFeatureExtractEx.argtypes = (c_void_p, POINTER(ASVLOFFSCREEN), POINTER(ASF_SingleFaceInfo), POINTER(ASF_FaceFeature))

#設(shè)置RGB/IR活體閾值,若不設(shè)置內(nèi)部默認(rèn)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的倍數(shù)

height in 圖片高度,YUYV/I420/NV21/NV12格式為2的倍數(shù)甥温;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 字節(jié)序排布
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 字節(jié)序排布
ASVL_PAF_GRAY 1793 8-bit IR圖像
ASVL_PAF_DEPTH_U16 3074 16-bit IR圖像

imgData in 圖像數(shù)據(jù)

detectedFaces in 多人臉信息

combinedMask in 1.檢測的屬性(ASF_AGE、ASF_GENDER跺讯、 ASF_FACE3DANGLE枢贿、ASF_LIVENESS),支持多選 2.檢測的屬性須在引擎初始化接口的combinedMask參數(shù)中啟用
#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 圖像數(shù)據(jù)
detectedFaces in 多人臉信息
combinedMask in
    1.檢測的屬性(ASF_AGE耀态、ASF_GENDER、 ASF_FACE3DANGLE暂雹、ASF_LIVENESS)首装,支持多選
    2.檢測的屬性須在引擎初始化接口的combinedMask參數(shù)中啟用
'''
processEx = dll.ASFProcessEx
processEx.restype = c_int32
processEx.argtypes = (c_void_p, POINTER(c_ubyte), ASF_MultiFaceInfo, c_int32)

#ASFGetAge 獲取年齡信息。
'''
hEngine in 引擎句柄
ageInfo out 檢測到的年齡信息數(shù)組
'''
getAge = dll.ASFGetAge
getAge.restype = c_int32
getAge.argtypes = (c_void_p, ASF_AgeInfo)

#ASFGetGender 獲取性別信息杭跪。
'''
hEngine in 引擎句柄
genderInfo out 檢測到的性別信息數(shù)組
'''
getGender = dll.ASFGetGender
getGender.restype = c_int32
getGender.argtypes = (c_void_p, ASF_GenderInfo)

#ASFGetFace3DAngle 獲取3D角度信息仙逻。
'''
hEngine in 引擎句柄
p3DAngleInfo out 檢測到的3D角度信息數(shù)組
'''
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的倍數(shù)
height in 圖片高度
format in 圖像顏色格式
imgData in 圖像數(shù)據(jù)
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 圖像數(shù)據(jù)
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.窗口的形式展現(xiàn) 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為對應(yīng)的圖片名即為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)

項目地址:碼云

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末庄蹋,一起剝皮案震驚了整個濱河市瞬内,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌限书,老刑警劉巖虫蝶,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異倦西,居然都是意外死亡能真,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來粉铐,“玉大人疼约,你說我怎么就攤上這事◎茫” “怎么了程剥?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長汤踏。 經(jīng)常有香客問我织鲸,道長,這世上最難降的妖魔是什么溪胶? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任搂擦,我火速辦了婚禮,結(jié)果婚禮上哗脖,老公的妹妹穿的比我還像新娘瀑踢。我一直安慰自己,他們只是感情好才避,可當(dāng)我...
    茶點故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布橱夭。 她就那樣靜靜地躺著,像睡著了一般工扎。 火紅的嫁衣襯著肌膚如雪徘钥。 梳的紋絲不亂的頭發(fā)上衔蹲,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天肢娘,我揣著相機(jī)與錄音,去河邊找鬼舆驶。 笑死橱健,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的沙廉。 我是一名探鬼主播拘荡,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼撬陵!你這毒婦竟也來了珊皿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤巨税,失蹤者是張志新(化名)和其女友劉穎蟋定,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體草添,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡驶兜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抄淑。...
    茶點故事閱讀 39,703評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡屠凶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出肆资,到底是詐尸還是另有隱情矗愧,我是刑警寧澤,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布郑原,位于F島的核電站贱枣,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏颤专。R本人自食惡果不足惜纽哥,卻給世界環(huán)境...
    茶點故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望栖秕。 院中可真熱鬧春塌,春花似錦、人聲如沸簇捍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽暑塑。三九已至吼句,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間事格,已是汗流浹背惕艳。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留驹愚,地道東北人远搪。 一個月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像逢捺,于是被迫代替她去往敵國和親谁鳍。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,601評論 2 353