houxiao
2017-04-28 9a3ef17d8b9f96fa05b5439c89bbfc2868d0f268
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#include "STFaceCache.h"
#include <MaterialBuffer.h>
#include <logger.h>
#include <map>
 
#include <sys/types.h>
#include <dirent.h>
 
#include "sample_face_search.h"
#include <cv_face.h>
 
#define FDP_FDR_INVALID FDP_FaceDetectResult(0, 0)
#define ENABLE_AUTO_CREATE_STFACEDB
#define ENABLE_SEARCH_IN_NEGATIVE_DBID
#define ENABLE_SEARCH_IN_NEGATIVE_DBID
#define RESULT_CONFIDENCE 0.70
 
struct STFaceCacheContext
{
    cv_handle_t handle_verify;
    cv_handle_t handle_detect;
 
    STFaceCacheContext() : handle_verify(nullptr), handle_detect(nullptr)
    {
    }
};
 
struct STFaceDBContext
{
    int dbid;
    std::string dbfname;
    std::string dbfpath;
    stface_handles handles;
    bool dbLoadOK;
    
    STFaceDBContext() : dbid(0), dbfname(), dbfpath(), handles(), dbLoadOK(false)
    {}
    
    bool init_db(const STFaceCacheContext& ctx)
    {
        handles.handle_verify = ctx.handle_verify;
        handles.handle_detect = ctx.handle_detect;
        if (handles.handle_db == nullptr)
        {
            dbLoadOK = stface_db_load(handles, db_full_path().c_str());
            dbLoadOK &= (handles.handle_db != nullptr);
        }
        else
        {
            dbLoadOK = true;
        }
        return dbLoadOK;
    }
    
    void close_db()
    {
        stface_db_save(handles, db_full_path().c_str());
        
        handles.handle_verify = nullptr;
        handles.handle_detect = nullptr;
        cv_verify_destroy_db(handles.handle_db);
        handles.handle_db = nullptr;
        dbLoadOK = false;
    }
    
    std::string db_full_path() const
    {
        if (dbfpath.empty() || dbfname.empty())
            return "";
        
        std::string fn(dbfpath);
        fn.append("/");
        fn.append(dbfname);
        return fn;
    }
};
 
typedef std::map<int, STFaceDBContext> stface_ctx_map_t; // <dbid, ctx>
 
STFaceCache::STFaceCache(const std::string& _stfacedbPath)
    : stfacedbPath(_stfacedbPath), stfaceModels(STFACESDK_BASE "/models"), 
    _dbContext(new stface_ctx_map_t), _cacheContext(new STFaceCacheContext)
{
    LOG_INFO << "st face db: " << stfacedbPath << LOG_ENDL;
    LOG_INFO << "st face sdk models: " << stfaceModels << LOG_ENDL;
}
 
STFaceCache::~STFaceCache()
{
    delete (stface_ctx_map_t*)_dbContext;
    _dbContext = nullptr;
    
    delete (STFaceCacheContext*)_cacheContext;
    _cacheContext = nullptr;
}
 
bool STFaceCache::init()
{
    STFaceCacheContext& cacheContext(*(STFaceCacheContext*)_cacheContext);
    
    if (stface_init_license("./license.lic") != 0)
    {
        LOG_ERROR << "stface_init_license failed" << LOG_ENDL;
        return false;
    }
    
    cv_face_algorithm_info();
    
    cv_result_t cv_result = cv_face_create_detector(&cacheContext.handle_detect, nullptr, CV_DETECT_ENABLE_ALIGN_21);
    if (cv_result != CV_OK)
    {
        LOGP(ERROR, "create detect handle failed, error code %d", cv_result);
        return false;
    }
    
    std::string modelsFile(stfaceModels);
    modelsFile.append("/verify.model");
    cv_result = cv_verify_create_handle(&cacheContext.handle_verify, modelsFile.c_str());
    if (cv_result != CV_OK)
    {
        LOGP(ERROR, "create verify handle failed, error code %d\n", cv_result);
        return false;
    }
    
    return true;
}
 
void STFaceCache::finit()
{
    STFaceCacheContext& cacheContext(*(STFaceCacheContext*)_cacheContext);
    
    cv_face_destroy_detector(cacheContext.handle_detect);
    cv_verify_destroy_handle(cacheContext.handle_verify);
    cacheContext.handle_detect = nullptr;
    cacheContext.handle_verify = nullptr;
}
 
bool STFaceCache::load_dbs()
{
    stface_ctx_map_t& dbContext(*(stface_ctx_map_t*)_dbContext);
    STFaceCacheContext& cacheContext(*(STFaceCacheContext*)_cacheContext);
    
    DIR* dp = opendir(stfacedbPath.c_str());
    if (dp != NULL)
    {
        struct dirent* ep;
        while(ep = readdir(dp))
        {
            //puts(ep->d_name);
            
            STFaceDBContext ctx;
            ctx.dbfname = ep->d_name;
            ctx.dbfpath = stfacedbPath;
            ctx.dbid = strtol(ctx.dbfname.c_str(), nullptr, 10);
            
            if (ctx.dbfname.find(".stfacedb") == std::string::npos)
                continue;
            
            if (ctx.dbid == 0)
                continue;
            
            dbContext.insert(std::make_pair(ctx.dbid, ctx));
        }
        closedir(dp);
    }
    else
    {
        LOG_ERROR << "Couldn't open the directory." << LOG_ENDL;
        return false;
    }
    
    for (stface_ctx_map_t::iterator iterCtx = dbContext.begin(); iterCtx != dbContext.end(); ++iterCtx)
    {
        STFaceDBContext& ctx(iterCtx->second);
        bool ret = ctx.init_db(cacheContext);
        LOG_INFO << "init stface db dbid=" << ctx.dbid << ", ret=" << ret << LOG_ENDL;
    }
    
    return true;
}
 
void STFaceCache::close_dbs()
{
    stface_ctx_map_t& dbContext(*(stface_ctx_map_t*)_dbContext);
    
    for (stface_ctx_map_t::iterator iterCtx = dbContext.begin(); iterCtx != dbContext.end(); ++iterCtx)
    {
        STFaceDBContext& ctx(iterCtx->second);
        ctx.close_db();
    }
}
 
FDP_FaceDetectResult STFaceCache::detect_neg(const STFaceImage& img)
{
    if (img.db_id <= 0)
    {
        return FDP_FDR_INVALID;
    }
    
#ifdef ENABLE_SEARCH_IN_NEGATIVE_DBID
            STFaceImage imgNeg(img);
            imgNeg.db_id = -1;
            return detect(imgNeg);
#else
            return FDP_FDR_INVALID;
#endif
}
 
FDP_FaceDetectResult STFaceCache::detect(const STFaceImage& img)
{
    stface_ctx_map_t& dbContext(*(stface_ctx_map_t*)_dbContext);
    
    LOG_WARN << "detect in dbid=" << img.db_id << LOG_ENDL;
    
    if (img.db_id == 0)
    {
        // search all db
        //#todo
    }
    else
    {
        stface_ctx_map_t::iterator iterCtx = dbContext.find(img.db_id);
        if (iterCtx == dbContext.end())
        {
            LOG_WARN << "no db find dbid=" << img.db_id << LOG_ENDL;
            return detect_neg(img);
        }
        
        STFaceDBContext& ctx(iterCtx->second);
        if (!ctx.dbLoadOK)
        {
            LOG_WARN << "dbLoadOK return false" << LOG_ENDL;
            return detect_neg(img);
        }
        
        top_idx_score_vect_t result;
        if (!stface_search_db(ctx.handles, img, result))
        {
            LOG_WARN << "stface_search_db return false" << LOG_ENDL;
            return detect_neg(img);
        }
        
        if (result.empty())
        {
            LOG_INFO << "stface_search_db return empty" << LOG_ENDL;
            return detect_neg(img);
        }
        
        LOGP(INFO, "stface_search_db return dbid=%d, idx=%d, score=%f", img.db_id, result[0].idx, result[0].score);
 
        if (result[0].score < RESULT_CONFIDENCE)
        {
            LOGP(INFO, "low score not accepted");
            return detect_neg(img);
        }
        
        return FDP_FaceDetectResult(img.db_id, result[0].idx);
    }
 
    return FDP_FDR_INVALID;
}
 
FDP_FaceDetectResult STFaceCache::add(const STFaceImage& img)
{
    stface_ctx_map_t& dbContext(*(stface_ctx_map_t*)_dbContext);
    STFaceCacheContext& cacheContext(*(STFaceCacheContext*)_cacheContext);
    
    LOG_WARN << "add in dbid=" << img.db_id << LOG_ENDL;
    
    if (img.db_id == 0)
    {
        LOG_WARN << "db_id=0 not ok" << LOG_ENDL;
        return FDP_FDR_INVALID;
    }
    
    stface_ctx_map_t::iterator iterCtx = dbContext.find(img.db_id);
    
#ifdef ENABLE_AUTO_CREATE_STFACEDB
    if (iterCtx == dbContext.end())
    {
        // create db
        STFaceDBContext ctx;
        char dbfname[50];
        sprintf(dbfname, "%d.stfacedb", img.db_id);
        ctx.dbfname = dbfname;
        ctx.dbfpath = stfacedbPath;
        ctx.dbid = img.db_id;
        ctx.init_db(cacheContext); // copy handlers
        
        if (!stface_db_create(ctx.handles, ctx.db_full_path().c_str()))
        {
            LOG_WARN << "stface_db_create return false" << LOG_ENDL;
            return FDP_FDR_INVALID;
        }
        
        ctx.dbLoadOK = true;
 
        dbContext.insert(std::make_pair(ctx.dbid, ctx));
        iterCtx = dbContext.find(img.db_id);
    }
#endif
    
    if (iterCtx == dbContext.end())
    {
        LOG_ERROR << "no stfacedb found" << LOG_ENDL;
        return FDP_FDR_INVALID;
    }
    
    STFaceDBContext& ctx(iterCtx->second);
    if (!ctx.dbLoadOK)
    {
        LOG_WARN << "dbLoadOK return false" << LOG_ENDL;
        return FDP_FDR_INVALID;
    }
    
    int idx = stface_db_add(ctx.handles, img);
    LOG_INFO << "stface_db_add dbid=" << img.db_id << ", idx=" << idx << LOG_ENDL;
    if (idx <= 1)
        return FDP_FDR_INVALID;
    else
        return FDP_FaceDetectResult(img.db_id, idx);
}