#include "IM_DLibWorker.h" #include #include "../../lib/alg/generic/md5.h" #include "../../lib/components/base/basicFunctionality.h" #define LOG( X ) m_pLog->Log( "WDLIB", this, X ) #ifdef DEBUG #define LOG_ERROR( X ) {\ char _tBfrErrMSG234[256];\ sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ m_pLog->Log( "WDLIB", this, _LOG_ERROR, _tBfrErrMSG234 );\ } #else #define LOG_ERROR( X ) m_pLog->Log( "WDLIB", this, _LOG_ERROR, X ); #endif // Constructor implementation IM_DlibWorker::IM_DlibWorker( config_setting_t * Settings ) : basicThread(), m_mBufferProtectorMutex(){ m_pLog = basicLogCollection::getInstance(); m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DLIB" ); m_pEvtHeap = basicEventHeap::getInstance(); m_pDBA = IM_DataBaseAdapter::getInstance(); // m_eBackendEngine = cv::dnn::DNN_BACKEND_DEFAULT; // m_eTargetDevice = cv::dnn::DNN_TARGET_CPU; m_pActiveJob = NULL; #ifdef DARKNET m_pDarknetDetector = NULL; #endif m_fDetectionProbability = .7f; m_bUseShapePredictor = false; m_bUseFaceRecognition = false; m_bDataIsActive = false; }; // Destructor implementation IM_DlibWorker::~IM_DlibWorker(){ #ifdef DARKNET if( m_pDarknetDetector ) delete( m_pDarknetDetector ); #endif }; bool IM_DlibWorker::create( void ){ char tBuff[256]; if( m_pSettings == NULL ){ return false; } else { config_setting_t * tSetting; tSetting = config_setting_get_member( m_pSettings, "PICTURES_BASE" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "PICTURES_BASE", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "/srv/vault" ); basicSettingsProvider::getInstance()->compromise(); LOG("No Pictures Base Path! Using default!"); }; sprintf( m_pPicturesBase, "%s", config_setting_get_string(tSetting)); tSetting = config_setting_get_member( m_pSettings, "FACEES_BASE" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "FACEES_BASE", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "/srv/vault/faces" ); basicSettingsProvider::getInstance()->compromise(); LOG("No Face Pictures Base Path! Using default!"); }; sprintf( m_pFacesBase, "%s", config_setting_get_string(tSetting)); tSetting = config_setting_get_member( m_pSettings, "USE_SHAPE_PREDICTOR" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "USE_SHAPE_PREDICTOR", CONFIG_TYPE_BOOL ); config_setting_set_bool( tSetting, 0 ); basicSettingsProvider::getInstance()->compromise(); LOG("No Class Map Usage Set! Using default!"); }; m_bUseShapePredictor = (bool) config_setting_get_bool(tSetting); if( m_bUseShapePredictor ) { tSetting = config_setting_get_member( m_pSettings, "USE_FACE_RECOGNITION" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "USE_FACE_RECOGNITION", CONFIG_TYPE_BOOL ); config_setting_set_bool( tSetting, 0 ); basicSettingsProvider::getInstance()->compromise(); LOG("No Class Map Usage Set! Using default!"); }; m_bUseFaceRecognition = (bool) config_setting_get_bool(tSetting); tSetting = config_setting_get_member( m_pSettings, "SHAPE_PREDICTOR_LANDMARKS" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "SHAPE_PREDICTOR_LANDMARKS", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "data/shape_predictor_5_face_landmarks.dat" ); basicSettingsProvider::getInstance()->compromise(); LOG("No Net Config File! Using default!"); }; sprintf( m_pShapePredictorPath, "%s", config_setting_get_string(tSetting)); if( m_bUseFaceRecognition ) { tSetting = config_setting_get_member( m_pSettings, "NET_CONFIG_FILE" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "NET_CONFIG_FILE", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "data/dlib_face_recognition_resnet_model_v1.dat" ); basicSettingsProvider::getInstance()->compromise(); LOG("No Net Weights File! Using default!"); }; sprintf( m_pNetModelPath, "%s", config_setting_get_string(tSetting)); }; } else m_bUseFaceRecognition = false; tSetting = config_setting_get_member( m_pSettings, "DETECTION_PROBABILITY" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "DETECTION_PROBABILITY", CONFIG_TYPE_FLOAT ); config_setting_set_float( tSetting, 0.5f ); basicSettingsProvider::getInstance()->compromise(); LOG("No Probability Set! Using default!"); }; m_fDetectionProbability = config_setting_get_float(tSetting); tSetting = config_setting_get_member( m_pSettings, "OUTPUT_CHOWN_USER" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "OUTPUT_CHOWN_USER", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "www-data" ); basicSettingsProvider::getInstance()->compromise(); LOG("No CHOWN USER! Using default!"); }; sprintf( m_sChownUser, "%s", config_setting_get_string(tSetting)); tSetting = config_setting_get_member( m_pSettings, "OUTPUT_CHOWN_GROUP" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "OUTPUT_CHOWN_GROUP", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "www-data" ); basicSettingsProvider::getInstance()->compromise(); LOG("No CHOWN GROUP! Using default!"); }; sprintf( m_sChownGroup, "%s", config_setting_get_string(tSetting)); /* tSetting = config_setting_get_member( m_pSettings, "USE_CLASS_MAP" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "USE_CLASS_MAP", CONFIG_TYPE_BOOL ); config_setting_set_bool( tSetting, 0 ); basicSettingsProvider::getInstance()->compromise(); LOG("No Class Map Usage Set! Using default!"); }; m_bUseClassMapping = (bool) config_setting_get_bool(tSetting); if( m_bUseClassMapping ) { char tMapFileName[1024]; FILE *fd; tSetting = config_setting_get_member( m_pSettings, "CLASS_MAP_FILE" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "CLASS_MAP_FILE", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "data/coco9k.map" ); basicSettingsProvider::getInstance()->compromise(); LOG("No Class Map File Set! Using default!"); }; sprintf( tMapFileName, "%s", config_setting_get_string(tSetting) ); fd = fopen( tMapFileName, "r" ); if( fd ) { uint32_t tV; uint32_t idx = 0; char tB[128]; while( !feof(fd) ) { if( fgets( tB, 128, fd ) ){ tV = atoi( tB )+1; m_vClassesMap.push_back( tV ); idx++; }; }; fclose( fd ); sprintf( tB, "Loadded %d classes map", idx ); LOG( tB ); } else { m_bUseClassMapping = false; }; }; tSetting = config_setting_get_member( m_pSettings, "NET_TARGET_DEVICE" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "NET_TARGET_DEVICE", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "CPU" ); basicSettingsProvider::getInstance()->compromise(); LOG("No Net Target Device! Using default!"); }; if( strstr( config_setting_get_string(tSetting), "CPU" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_CPU; if( strstr( config_setting_get_string(tSetting), "OPENCL_FP16" )!=NULL ){ m_eTargetDevice = cv::dnn::DNN_TARGET_OPENCL_FP16; } else { if( strstr( config_setting_get_string(tSetting), "OPENCL" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_OPENCL; }; if( strstr( config_setting_get_string(tSetting), "MYRIAD" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_MYRIAD; if( strstr( config_setting_get_string(tSetting), "VULKAN" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_VULKAN; if( strstr( config_setting_get_string(tSetting), "FPGA" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_FPGA; if( strstr( config_setting_get_string(tSetting), "CUDA_FP16" )!=NULL ){ m_eTargetDevice = cv::dnn::DNN_TARGET_CUDA_FP16; } else { if( strstr( config_setting_get_string(tSetting), "CUDA" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_CUDA; }; if( strstr( config_setting_get_string(tSetting), "HDDL" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_HDDL; sprintf( tBuff, "Device: %s", config_setting_get_string(tSetting) ); LOG( tBuff ); tSetting = config_setting_get_member( m_pSettings, "NET_BACKEND_ENGINE" ); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "NET_BACKEND_ENGINE", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "DEFAULT" ); basicSettingsProvider::getInstance()->compromise(); LOG("No Net Backend Engine! Using default!"); }; if( strstr( config_setting_get_string(tSetting), "DEFAULT" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_DEFAULT; if( strstr( config_setting_get_string(tSetting), "HALIDE" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_HALIDE; if( strstr( config_setting_get_string(tSetting), "INFERENCE" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_INFERENCE_ENGINE; if( strstr( config_setting_get_string(tSetting), "OPENCV" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_OPENCV; if( strstr( config_setting_get_string(tSetting), "VKCOM" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_VKCOM; if( strstr( config_setting_get_string(tSetting), "CUDA" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_CUDA; sprintf( tBuff, "Engine: %s", config_setting_get_string(tSetting) ); LOG( tBuff ); */ basicSettingsProvider::getInstance()->validate(); }; if( m_bUseShapePredictor ) { if( m_bUseFaceRecognition ) { sprintf( tBuff, "loading Data from disk... Shape: %s Face: %s", m_pShapePredictorPath, m_pNetModelPath ); } else { sprintf( tBuff, "loading Data from disk... Shape Predictor: %s ", m_pShapePredictorPath ); }; LOG( tBuff ); if(!fileExist( m_pShapePredictorPath )) { LOG_ERROR("No Shape Predictor file exists!"); return false; }; if( m_bUseFaceRecognition ) { if(!fileExist( m_pNetModelPath )) { LOG_ERROR("No Net Model file exists!"); return false; }; } } m_oFaceDetector = get_frontal_face_detector(); if( m_bUseShapePredictor ) { deserialize( m_pShapePredictorPath ) >> m_oShapePredictor; if( m_bUseFaceRecognition ) { deserialize( m_pNetModelPath ) >> m_oNet; }; }; return init(); }; std::vector> jitter_image( const matrix& img ){ // All this function does is make 100 copies of img, all slightly jittered by being // zoomed, rotated, and translated a little bit differently. They are also randomly // mirrored left to right. thread_local dlib::rand rnd; std::vector> crops; for (int i = 0; i < 100; ++i) crops.push_back(jitter_image(img,rnd)); return crops; }; CSTR IM_DlibWorker::m_fSaveFace( matrix &Picture, CSTR md5, uint32_t index ){ char tPathSrc[1024]; char tPathDest[1024]; CSTR nMd5; CSTR nPath; sprintf( tPathSrc, "%s/%s_%d.jpg", m_pFacesBase, md5, index ); LOG("Save Face"); LOG( tPathSrc ); save_jpeg( Picture, tPathSrc, 75 ); nMd5 = MD5File( tPathSrc ); nPath = buildMd5Path( m_pFacesBase, nMd5, 0755, m_sChownUser, m_sChownGroup ); sprintf( tPathDest, "%s/%s.jpg", nPath, nMd5 ); free( nPath ); //fileCopy( tPathSrc, tPathDest ); //remove( tPathSrc ); rename ( tPathSrc, tPathDest ); ch_chown( tPathDest, m_sChownUser, m_sChownGroup ); return nMd5; }; IM_RESULT *IM_DlibWorker::m_fImageAnalyzer( cv::Mat &Pic ){ IM_RESULT * retVal = NULL; cv_image Picture(Pic); std::vector> faces; std::vector dbIDs; uint32_t idx = 0; CSTR tVAL = NULL; for( auto face : m_oFaceDetector( Picture ) ){ //dlib::rectangle face if( m_bUseShapePredictor ) { auto shape = m_oShapePredictor( Picture, face ); matrix face_chip; extract_image_chip( Picture, get_face_chip_details( shape, 150, 0.25 ), face_chip ); tVAL = m_fSaveFace( face_chip, m_pActiveJob->md5, idx ); faces.push_back( move( face_chip ) ); } else { matrix face_chip; extract_image_chip( Picture, face, face_chip ); tVAL = m_fSaveFace( face_chip, m_pActiveJob->md5, idx ); }; if( tVAL!= NULL ) { uint32_t tID; tID = m_pDBA->insertItemFace( m_pActiveJob->dbID, tVAL, face.left(), face.top(), face.width(), face.height() ); dbIDs.push_back( tID ); char tB[64]; sprintf(tB,"ID:%d", tID); LOG(tB); free( tVAL ); tVAL = NULL; }; idx++; }; if( m_bUseShapePredictor ) { //if (faces.size() == 0){ // cout << "No faces found in image!" << endl; // return 1; //} if( m_bUseFaceRecognition ) { // This call asks the DNN to convert each face image in faces into a 128D vector. // In this 128D vector space, images from the same person will be close to each other // but vectors from different people will be far apart. So we can use these vectors to // identify if a pair of images are from the same person or from different people. if( faces.size() ) { //LOG("Have Detected Faces!"); //std::vector> face_descriptors = m_oNet( faces ); try{ for( int idx = 0; idx < faces.size(); idx++ ) { matrix face_descriptor = mean( mat( m_oNet( jitter_image( faces[idx] ) ) ) ); //matrix face_descriptor = m_oNet( faces[0] ); //LOG("Classification Done!"); for( int i = 0; i < face_descriptor.size(); i++ ) m_pDBA->updateItemFace( dbIDs[idx], i, face_descriptor( i, 0 ) ); }; } catch ( std::exception& e ){ LOG_ERROR( e.what() ); }; } else { LOG("No Faces Found!"); }; //std::vector> face_descriptors = m_oNet( faces ); // In particular, one simple thing we can do is face clustering. This next bit of code // creates a graph of connected faces and then uses the Chinese whispers graph clustering // algorithm to identify how many people there are and which faces belong to whom. /* std::vector edges; for (size_t i = 0; i < face_descriptors.size(); ++i){ for (size_t j = i; j < face_descriptors.size(); ++j){ // Faces are connected in the graph if they are close enough. Here we check if // the distance between two face descriptors is less than 0.6, which is the // decision threshold the network was trained to use. Although you can // certainly use any other threshold you find useful. if (length(face_descriptors[i]-face_descriptors[j]) < 0.6) edges.push_back(sample_pair(i,j)); }; }; std::vector labels; const auto num_clusters = chinese_whispers(edges, labels); */ // This will correctly indicate that there are 4 people in the image. //cout << "number of people found in the image: "<< num_clusters << endl; // Now let's display the face clustering results on the screen. You will see that it // correctly grouped all the faces. /* std::vector win_clusters(num_clusters); for( size_t cluster_id = 0; cluster_id < num_clusters; ++cluster_id ){ std::vector> temp; for( size_t j = 0; j < labels.size(); ++j ){ if (cluster_id == labels[j]) temp.push_back(faces[j]); }; win_clusters[cluster_id].set_title("face cluster " + cast_to_string(cluster_id)); win_clusters[cluster_id].set_image(tile_images(temp)); }; // Finally, let's print one of the face descriptors to the screen. cout << "face descriptor for one face: " << trans(face_descriptors[0]) << endl; // It should also be noted that face recognition accuracy can be improved if jittering // is used when creating face descriptors. In particular, to get 99.38% on the LFW // benchmark you need to use the jitter_image() routine to compute the descriptors, // like so: matrix face_descriptor = mean(mat(net(jitter_image(faces[0])))); cout << "jittered face descriptor for one face: " << trans(face_descriptor) << endl; // If you use the model without jittering, as we did when clustering the bald guys, it // gets an accuracy of 99.13% on the LFW benchmark. So jittering makes the whole // procedure a little more accurate but makes face descriptor calculation slower. */ }; }; return retVal; }; void IM_DlibWorker::m_fThreadProc( void ){ m_bThreadStatus = TH_WORKING; EVENT_CONTAINER *EVT_PTR = NULL; while( m_bThreadStatus < TH_ENDED ) { while (!m_bDataIsActive && m_bThreadStatus < TH_ENDED ) SLEEP( 20 ); if( m_mBufferProtectorMutex.try_lock() ){ if( m_bDataIsActive ){ EVT_PTR =(EVENT_CONTAINER *) malloc(sizeof(EVENT_CONTAINER)); if( EVT_PTR ) { memset( EVT_PTR, 0, sizeof(EVENT_CONTAINER)); EVT_PTR->m_eClass = EVT_CLASS_IMAGE; EVT_PTR->m_eType = EVT_READY; if( IM_RESULT *tData = m_fImageAnalyzer( m_oWorkingMat ) ){ //generate detection event EVT_PTR->m_pEvtData = tData; } else { //generate NOT detection event EVT_PTR->m_pEvtData = NULL; }; }; m_pActiveJob = NULL; m_bDataIsActive = false; }; m_mBufferProtectorMutex.unlock(); }; if( EVT_PTR != NULL ) { m_pEvtHeap->broadcast( EVT_PTR ); EVT_PTR = NULL; }; }; }; bool IM_DlibWorker::enqueueJob( IM_JOB *ptr ){ if( ptr ) { char tPath[1024]; char p1[3]; char p2[3]; char p3[3]; LOG( ptr->md5 ); memcpy( p1, ptr->md5 , 2); p1[2]=(char)0; memcpy( p2, ptr->md5+2, 2); p2[2]=(char)0; memcpy( p3, ptr->md5+4, 2); p3[2]=(char)0; switch( ptr->image_type ) { case IM_ITEM_TYPE_JPEG: sprintf( tPath, "%s/%s/%s/%s/%s.jpg", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; case IM_ITEM_TYPE_PNG: sprintf( tPath, "%s/%s/%s/%s/%s.png", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; case IM_ITEM_TYPE_GIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; case IM_ITEM_TYPE_AGIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; case IM_ITEM_TYPE_TIFF: sprintf( tPath, "%s/%s/%s/%s/%s.tiff", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; }; #ifdef DEBUG LOG( tPath ); #endif Mat Frame = cv::imread( tPath, IMREAD_COLOR ); try{ while( m_bThreadStatus < TH_ENDED ) { if( m_mBufferProtectorMutex.try_lock() ) { Frame.copyTo( m_oWorkingMat ); #ifdef DEBUG cv::imwrite("cur-test-img.jpg", m_oWorkingMat ); //save_jpeg( m_oInputImg, "cur-test-img.jpg", 75 ); #endif m_bDataIsActive = true; m_pActiveJob = ptr; m_mBufferProtectorMutex.unlock(); return true; } else SLEEP(5); }; } catch ( exception e ){ LOG_ERROR( "Failure during Image Read!" ); }; }; return false; }; #undef LOG #undef LOG_ERROR