You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

350 lines
16 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "IM_DnnWorker.h"
  2. #include "../../lib/components/base/basicFunctionality.h"
  3. #define LOG( X ) m_pLog->Log( "WDNN", this, X )
  4. #ifdef DEBUG
  5. #define LOG_ERROR( X ) {\
  6. char _tBfrErrMSG234[256];\
  7. sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  8. m_pLog->Log( "WDNN", this, _LOG_ERROR, _tBfrErrMSG234 );\
  9. }
  10. #else
  11. #define LOG_ERROR( X ) m_pLog->Log( "WDNN", this, _LOG_ERROR, X );
  12. #endif
  13. // Constructor implementation
  14. IM_DnnWorker::IM_DnnWorker( config_setting_t * Settings ) : basicThread(), m_mBufferProtectorMutex(){
  15. m_pLog = basicLogCollection::getInstance();
  16. m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DNN" );
  17. m_pEvtHeap = basicEventHeap::getInstance();
  18. m_eBackendEngine = cv::dnn::DNN_BACKEND_DEFAULT;
  19. m_eTargetDevice = cv::dnn::DNN_TARGET_CPU;
  20. m_pActiveJob = NULL;
  21. #ifdef DARKNET
  22. m_pDarknetDetector = NULL;
  23. #endif
  24. m_bDataIsActive = false;
  25. };
  26. // Destructor implementation
  27. IM_DnnWorker::~IM_DnnWorker(){
  28. #ifdef DARKNET
  29. if( m_pDarknetDetector ) delete( m_pDarknetDetector );
  30. #endif
  31. };
  32. bool IM_DnnWorker::create( void ){
  33. char tBuff[256];
  34. if( m_pSettings == NULL ){
  35. return false;
  36. } else {
  37. config_setting_t * tSetting;
  38. tSetting = config_setting_get_member( m_pSettings, "PICTURES_BASE" );
  39. if( tSetting == NULL ){
  40. tSetting = config_setting_add(m_pSettings, "PICTURES_BASE", CONFIG_TYPE_STRING );
  41. config_setting_set_string( tSetting, "/srv/vault" );
  42. basicSettingsProvider::getInstance()->compromise();
  43. LOG("No Pictures Base Path! Using default!");
  44. };
  45. sprintf( m_pPicturesBase, "%s", config_setting_get_string(tSetting));
  46. tSetting = config_setting_get_member( m_pSettings, "NET_CONFIG_FILE" );
  47. if( tSetting == NULL ){
  48. tSetting = config_setting_add(m_pSettings, "NET_CONFIG_FILE", CONFIG_TYPE_STRING );
  49. config_setting_set_string( tSetting, "conf/yolo9000.cfg" );
  50. basicSettingsProvider::getInstance()->compromise();
  51. LOG("No Net Config File! Using default!");
  52. };
  53. sprintf( m_pConfigPath, "%s", config_setting_get_string(tSetting));
  54. tSetting = config_setting_get_member( m_pSettings, "NET_WEIGHTS_FILE" );
  55. if( tSetting == NULL ){
  56. tSetting = config_setting_add(m_pSettings, "NET_WEIGHTS_FILE", CONFIG_TYPE_STRING );
  57. config_setting_set_string( tSetting, "data/yolo9000.weights" );
  58. basicSettingsProvider::getInstance()->compromise();
  59. LOG("No Net Weights File! Using default!");
  60. };
  61. sprintf( m_pWeightsPath, "%s", config_setting_get_string(tSetting));
  62. tSetting = config_setting_get_member( m_pSettings, "DETECTION_PROBABILITY" );
  63. if( tSetting == NULL ){
  64. tSetting = config_setting_add(m_pSettings, "DETECTION_PROBABILITY", CONFIG_TYPE_FLOAT );
  65. config_setting_set_float( tSetting, 0.5f );
  66. basicSettingsProvider::getInstance()->compromise();
  67. LOG("No Probability Set! Using default!");
  68. };
  69. m_fDetectionProbability = config_setting_get_float(tSetting);
  70. tSetting = config_setting_get_member( m_pSettings, "USE_CLASS_MAP" );
  71. if( tSetting == NULL ){
  72. tSetting = config_setting_add(m_pSettings, "USE_CLASS_MAP", CONFIG_TYPE_BOOL );
  73. config_setting_set_bool( tSetting, 0 );
  74. basicSettingsProvider::getInstance()->compromise();
  75. LOG("No Class Map Usage Set! Using default!");
  76. };
  77. m_bUseClassMapping = (bool) config_setting_get_bool(tSetting);
  78. if( m_bUseClassMapping ) {
  79. char tMapFileName[1024];
  80. FILE *fd;
  81. tSetting = config_setting_get_member( m_pSettings, "CLASS_MAP_FILE" );
  82. if( tSetting == NULL ){
  83. tSetting = config_setting_add(m_pSettings, "CLASS_MAP_FILE", CONFIG_TYPE_STRING );
  84. config_setting_set_string( tSetting, "data/coco9k.map" );
  85. basicSettingsProvider::getInstance()->compromise();
  86. LOG("No Class Map File Set! Using default!");
  87. };
  88. sprintf( tMapFileName, "%s", config_setting_get_string(tSetting) );
  89. fd = fopen( tMapFileName, "r" );
  90. if( fd ) {
  91. uint32_t tV;
  92. uint32_t idx = 0;
  93. char tB[128];
  94. while( !feof(fd) ) {
  95. if( fgets( tB, 128, fd ) ){
  96. tV = atoi( tB )+1;
  97. m_vClassesMap.push_back( tV );
  98. idx++;
  99. };
  100. };
  101. fclose( fd );
  102. sprintf( tB, "Loadded %d classes map", idx );
  103. LOG( tB );
  104. } else {
  105. m_bUseClassMapping = false;
  106. };
  107. };
  108. tSetting = config_setting_get_member( m_pSettings, "NET_TARGET_DEVICE" );
  109. if( tSetting == NULL ){
  110. tSetting = config_setting_add(m_pSettings, "NET_TARGET_DEVICE", CONFIG_TYPE_STRING );
  111. config_setting_set_string( tSetting, "CPU" );
  112. basicSettingsProvider::getInstance()->compromise();
  113. LOG("No Net Target Device! Using default!");
  114. };
  115. if( strstr( config_setting_get_string(tSetting), "CPU" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_CPU;
  116. if( strstr( config_setting_get_string(tSetting), "OPENCL_FP16" )!=NULL ){
  117. m_eTargetDevice = cv::dnn::DNN_TARGET_OPENCL_FP16;
  118. } else {
  119. if( strstr( config_setting_get_string(tSetting), "OPENCL" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_OPENCL;
  120. };
  121. if( strstr( config_setting_get_string(tSetting), "MYRIAD" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_MYRIAD;
  122. if( strstr( config_setting_get_string(tSetting), "VULKAN" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_VULKAN;
  123. if( strstr( config_setting_get_string(tSetting), "FPGA" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_FPGA;
  124. if( strstr( config_setting_get_string(tSetting), "CUDA_FP16" )!=NULL ){
  125. m_eTargetDevice = cv::dnn::DNN_TARGET_CUDA_FP16;
  126. } else {
  127. if( strstr( config_setting_get_string(tSetting), "CUDA" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_CUDA;
  128. };
  129. if( strstr( config_setting_get_string(tSetting), "HDDL" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_HDDL;
  130. sprintf( tBuff, "Device: %s", config_setting_get_string(tSetting) );
  131. LOG( tBuff );
  132. tSetting = config_setting_get_member( m_pSettings, "NET_BACKEND_ENGINE" );
  133. if( tSetting == NULL ){
  134. tSetting = config_setting_add(m_pSettings, "NET_BACKEND_ENGINE", CONFIG_TYPE_STRING );
  135. config_setting_set_string( tSetting, "DEFAULT" );
  136. basicSettingsProvider::getInstance()->compromise();
  137. LOG("No Net Backend Engine! Using default!");
  138. };
  139. if( strstr( config_setting_get_string(tSetting), "DEFAULT" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_DEFAULT;
  140. if( strstr( config_setting_get_string(tSetting), "HALIDE" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_HALIDE;
  141. if( strstr( config_setting_get_string(tSetting), "INFERENCE" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_INFERENCE_ENGINE;
  142. if( strstr( config_setting_get_string(tSetting), "OPENCV" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_OPENCV;
  143. if( strstr( config_setting_get_string(tSetting), "VKCOM" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_VKCOM;
  144. if( strstr( config_setting_get_string(tSetting), "CUDA" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_CUDA;
  145. sprintf( tBuff, "Engine: %s", config_setting_get_string(tSetting) );
  146. LOG( tBuff );
  147. basicSettingsProvider::getInstance()->validate();
  148. };
  149. sprintf( tBuff, "loading DNN from disk... CONF: %s WEIGHT: %s", m_pConfigPath, m_pWeightsPath );
  150. LOG( tBuff );
  151. if(!fileExist( m_pConfigPath )) {
  152. LOG_ERROR("No Config file exists!");
  153. return false;
  154. };
  155. if(!fileExist( m_pWeightsPath )) {
  156. LOG_ERROR("No Weight file exists!");
  157. return false;
  158. };
  159. #ifdef DARKNET
  160. try {
  161. m_pDarknetDetector = new Detector( m_pConfigPath, m_pWeightsPath );
  162. if( m_pDarknetDetector ) {
  163. LOG("DarkNet Detector Created");
  164. } else {
  165. LOG_ERROR("Failure during DarkNet Detector Creation!");
  166. };
  167. } catch ( exception e ) {
  168. LOG_ERROR( e.what() );
  169. };
  170. #else
  171. m_net = cv::dnn::readNetFromDarknet( m_pConfigPath, m_pWeightsPath );
  172. m_net.setPreferableBackend( m_eBackendEngine );
  173. m_net.setPreferableTarget( m_eTargetDevice );
  174. std::vector<String> outNames = m_net.getUnconnectedOutLayersNames();
  175. LOG("OutNames");
  176. for( std::vector<String>::iterator idx = outNames.begin(); idx < outNames.end(); idx++ ) {
  177. LOG( (*idx).c_str() );
  178. };
  179. #endif
  180. return init();
  181. };
  182. IM_RESULT *IM_DnnWorker::m_fImageAnalyzer( Mat &Picture ){
  183. Size inpSize;
  184. bool swapRB = true; //BGR->RGB
  185. double scale = 1.0;///255.0;
  186. Scalar mean;
  187. IM_RESULT * retVal = NULL;
  188. inpSize.width = Picture.cols;
  189. inpSize.height = Picture.rows;
  190. #ifndef DARKNET
  191. try {
  192. LOG("Create a 4D blob from a frame");
  193. //cv::resize( m_oWorkingMat, m_oWorkingMat, cv::Size(416, 416));
  194. Mat blob = cv::dnn::blobFromImage( Picture, scale, Size(416, 416), mean, swapRB, false, CV_8U );
  195. if( blob.empty() ) {
  196. LOG_ERROR("Failure Creating Blob!");
  197. return retVal;
  198. };
  199. // construct a blob from the input frame and then perform a forward
  200. // pass of the YOLO object detector, giving us our bounding boxes
  201. // and associated probabilities
  202. //blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False )
  203. //net.setInput(blob)
  204. //layerOutputs = net.forward(ln)
  205. // Run a model.
  206. LOG("Set BLOB to NET");
  207. m_net.setInput( blob );
  208. //std::vector<Mat> outs;
  209. //std::vector<String> outNames = m_net.getUnconnectedOutLayersNames();
  210. Mat outMat = m_net.forward( String( "detection_out" ));
  211. LOG("DONE!");
  212. /*
  213. if( m_net.getLayer(0)->outputNameToIndex("im_info") != -1 ){
  214. // Faster-RCNN or R-FCN
  215. //resize( Picture, Picture, inpSize );
  216. cv::resize( Picture, Picture, cv::Size(416, 416));
  217. Mat imInfo = ( Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
  218. m_net.setInput( imInfo, "im_info" );
  219. };
  220. */
  221. } catch ( cv::Exception& e ) {
  222. LOG_ERROR("Catched Exception");
  223. LOG_ERROR( e.what() );
  224. };
  225. #else
  226. std::shared_ptr<image_t> img = m_pDarknetDetector->mat_to_image_resize( Picture );
  227. std::vector<bbox_t> result_vec;
  228. //result_vec = detector.detect_resized( * img, inpSize.width, inpSize.height, thresh, true);
  229. result_vec = m_pDarknetDetector->detect_resized( *img, inpSize.width, inpSize.height, m_fDetectionProbability, true);
  230. if( result_vec.size() ) {
  231. retVal = (IM_RESULT *)malloc(sizeof(IM_RESULT));
  232. if( retVal ) {
  233. retVal->pJOB = m_pActiveJob;
  234. retVal->nBoxCount = result_vec.size();
  235. retVal->boxes = (IM_CLASS_BOUNDARY_BOX *) calloc( retVal->nBoxCount,sizeof(IM_CLASS_BOUNDARY_BOX));
  236. if( retVal->boxes ) {
  237. for( int i=0; i< result_vec.size(); i++ ) {
  238. bbox_t * b = &(result_vec.at(i));
  239. retVal->boxes[i].weight = b->prob;
  240. retVal->boxes[i].x = b->x;
  241. retVal->boxes[i].y = b->y;
  242. retVal->boxes[i].width = b->w;
  243. retVal->boxes[i].height = b->h;
  244. if( m_bUseClassMapping ){
  245. retVal->boxes[i].classID = m_vClassesMap[b->obj_id];
  246. } else {
  247. retVal->boxes[i].classID = b->obj_id;
  248. };
  249. #ifdef DEBUG
  250. char msg[256];
  251. sprintf( msg, "[%d] Class: %d Prob: %.2f X:%d Y:%d W:%d H:%d", i, retVal->boxes[i].classID, retVal->boxes[i].weight, b->x, b->y, b->w, b->h );
  252. LOG( msg );
  253. #endif
  254. };
  255. } else {
  256. free(retVal);
  257. retVal = NULL;
  258. };
  259. };
  260. };
  261. #endif
  262. return retVal;
  263. };
  264. void IM_DnnWorker::m_fThreadProc( void ){
  265. m_bThreadStatus = TH_WORKING;
  266. basicEvent *EVT_PTR = NULL;
  267. while( m_bThreadStatus < TH_ENDED ) {
  268. while (!m_bDataIsActive && m_bThreadStatus < TH_ENDED ) SLEEP( 20 );
  269. if( m_mBufferProtectorMutex.try_lock() ){
  270. if( m_bDataIsActive ){
  271. EVT_PTR =(basicEvent *) malloc(sizeof(basicEvent));
  272. if( EVT_PTR ) {
  273. memset( EVT_PTR, 0, sizeof(basicEvent));
  274. EVT_PTR->m_eClass = EVT_CLASS_IMAGE;
  275. EVT_PTR->m_eType = EVT_READY;
  276. if( IM_RESULT *tData = m_fImageAnalyzer( m_oWorkingMat ) ){
  277. //generate detection event
  278. EVT_PTR->m_pEvtData = tData;
  279. } else {
  280. //generate NOT detection event
  281. EVT_PTR->m_pEvtData = NULL;
  282. };
  283. };
  284. m_pActiveJob = NULL;
  285. m_bDataIsActive = false;
  286. };
  287. m_mBufferProtectorMutex.unlock();
  288. };
  289. if( EVT_PTR != NULL ) {
  290. m_pEvtHeap->broadcast( EVT_PTR );
  291. EVT_PTR = NULL;
  292. };
  293. };
  294. };
  295. bool IM_DnnWorker::enqueueJob( IM_JOB *ptr ){
  296. if( ptr ) {
  297. char tPath[1024];
  298. char p1[3];
  299. char p2[3];
  300. char p3[3];
  301. LOG( ptr->md5 );
  302. memcpy( p1, ptr->md5 , 2); p1[2]=(char)0;
  303. memcpy( p2, ptr->md5+2, 2); p2[2]=(char)0;
  304. memcpy( p3, ptr->md5+4, 2); p3[2]=(char)0;
  305. switch( ptr->type ) {
  306. case IM_ITEM_TYPE_JPEG: sprintf( tPath, "%s/%s/%s/%s/%s.jpg", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  307. case IM_ITEM_TYPE_PNG: sprintf( tPath, "%s/%s/%s/%s/%s.png", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  308. case IM_ITEM_TYPE_GIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  309. case IM_ITEM_TYPE_AGIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  310. case IM_ITEM_TYPE_TIFF: sprintf( tPath, "%s/%s/%s/%s/%s.tiff", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  311. };
  312. #ifdef DEBUG
  313. LOG( tPath );
  314. #endif
  315. Mat Frame = cv::imread( tPath, IMREAD_COLOR );
  316. if( !Frame.empty() ){
  317. while( m_bThreadStatus < TH_ENDED ) {
  318. if( m_mBufferProtectorMutex.try_lock() ) {
  319. Frame.copyTo( m_oWorkingMat );
  320. #ifdef DEBUG
  321. cv::imwrite("cur-test-img.jpg", m_oWorkingMat );
  322. #endif
  323. m_bDataIsActive = true;
  324. m_pActiveJob = ptr;
  325. m_mBufferProtectorMutex.unlock();
  326. return true;
  327. };
  328. SLEEP(5);
  329. };
  330. } else {
  331. LOG_ERROR( "Failure during Image Read!" );
  332. };
  333. };
  334. return false;
  335. };
  336. #undef LOG
  337. #undef LOG_ERROR