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.

354 lines
16 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
​
5 years ago
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. LOG("Trying Load DARKNET");
  162. m_pDarknetDetector = new Detector( m_pConfigPath, m_pWeightsPath );
  163. LOG("After New ...");
  164. if( m_pDarknetDetector ) {
  165. LOG("DarkNet Detector Created");
  166. } else {
  167. LOG_ERROR("Failure during DarkNet Detector Creation!");
  168. };
  169. } catch ( exception e ) {
  170. LOG_ERROR( e.what() );
  171. };
  172. #else
  173. LOG("Trying Load CV::DARKNET");
  174. m_net = cv::dnn::readNetFromDarknet( m_pConfigPath, m_pWeightsPath );
  175. m_net.setPreferableBackend( m_eBackendEngine );
  176. m_net.setPreferableTarget( m_eTargetDevice );
  177. std::vector<String> outNames = m_net.getUnconnectedOutLayersNames();
  178. LOG("OutNames");
  179. for( std::vector<String>::iterator idx = outNames.begin(); idx < outNames.end(); idx++ ) {
  180. LOG( (*idx).c_str() );
  181. };
  182. #endif
  183. LOG("ALL Good ... ");
  184. return init();
  185. };
  186. IM_RESULT *IM_DnnWorker::m_fImageAnalyzer( Mat &Picture ){
  187. Size inpSize;
  188. bool swapRB = true; //BGR->RGB
  189. double scale = 1.0;///255.0;
  190. Scalar mean;
  191. IM_RESULT * retVal = NULL;
  192. inpSize.width = Picture.cols;
  193. inpSize.height = Picture.rows;
  194. #ifndef DARKNET
  195. try {
  196. LOG("Create a 4D blob from a frame");
  197. //cv::resize( m_oWorkingMat, m_oWorkingMat, cv::Size(416, 416));
  198. Mat blob = cv::dnn::blobFromImage( Picture, scale, Size(416, 416), mean, swapRB, false, CV_8U );
  199. if( blob.empty() ) {
  200. LOG_ERROR("Failure Creating Blob!");
  201. return retVal;
  202. };
  203. // construct a blob from the input frame and then perform a forward
  204. // pass of the YOLO object detector, giving us our bounding boxes
  205. // and associated probabilities
  206. //blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False )
  207. //net.setInput(blob)
  208. //layerOutputs = net.forward(ln)
  209. // Run a model.
  210. LOG("Set BLOB to NET");
  211. m_net.setInput( blob );
  212. //std::vector<Mat> outs;
  213. //std::vector<String> outNames = m_net.getUnconnectedOutLayersNames();
  214. Mat outMat = m_net.forward( String( "detection_out" ));
  215. LOG("DONE!");
  216. /*
  217. if( m_net.getLayer(0)->outputNameToIndex("im_info") != -1 ){
  218. // Faster-RCNN or R-FCN
  219. //resize( Picture, Picture, inpSize );
  220. cv::resize( Picture, Picture, cv::Size(416, 416));
  221. Mat imInfo = ( Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
  222. m_net.setInput( imInfo, "im_info" );
  223. };
  224. */
  225. } catch ( cv::Exception& e ) {
  226. LOG_ERROR("Catched Exception");
  227. LOG_ERROR( e.what() );
  228. };
  229. #else
  230. std::shared_ptr<image_t> img = m_pDarknetDetector->mat_to_image_resize( Picture );
  231. std::vector<bbox_t> result_vec;
  232. //result_vec = detector.detect_resized( * img, inpSize.width, inpSize.height, thresh, true);
  233. result_vec = m_pDarknetDetector->detect_resized( *img, inpSize.width, inpSize.height, m_fDetectionProbability, true);
  234. if( result_vec.size() ) {
  235. retVal = (IM_RESULT *)malloc(sizeof(IM_RESULT));
  236. if( retVal ) {
  237. retVal->pJOB = m_pActiveJob;
  238. retVal->nBoxCount = result_vec.size();
  239. retVal->boxes = (IM_CLASS_BOUNDARY_BOX *) calloc( retVal->nBoxCount,sizeof(IM_CLASS_BOUNDARY_BOX));
  240. if( retVal->boxes ) {
  241. for( int i=0; i< result_vec.size(); i++ ) {
  242. bbox_t * b = &(result_vec.at(i));
  243. retVal->boxes[i].weight = b->prob;
  244. retVal->boxes[i].x = b->x;
  245. retVal->boxes[i].y = b->y;
  246. retVal->boxes[i].width = b->w;
  247. retVal->boxes[i].height = b->h;
  248. if( m_bUseClassMapping ){
  249. retVal->boxes[i].classID = m_vClassesMap[b->obj_id];
  250. } else {
  251. retVal->boxes[i].classID = b->obj_id;
  252. };
  253. #ifdef DEBUG
  254. char msg[256];
  255. 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 );
  256. LOG( msg );
  257. #endif
  258. };
  259. } else {
  260. free(retVal);
  261. retVal = NULL;
  262. };
  263. };
  264. };
  265. #endif
  266. return retVal;
  267. };
  268. void IM_DnnWorker::m_fThreadProc( void ){
  269. m_bThreadStatus = TH_WORKING;
  270. EVENT_CONTAINER *EVT_PTR = NULL;
  271. while( m_bThreadStatus < TH_ENDED ) {
  272. while (!m_bDataIsActive && m_bThreadStatus < TH_ENDED ) SLEEP( 20 );
  273. if( m_mBufferProtectorMutex.try_lock() ){
  274. if( m_bDataIsActive ){
  275. EVT_PTR =(EVENT_CONTAINER *) malloc(sizeof(EVENT_CONTAINER));
  276. if( EVT_PTR ) {
  277. memset( EVT_PTR, 0, sizeof(EVENT_CONTAINER));
  278. EVT_PTR->m_eClass = EVT_CLASS_IMAGE;
  279. EVT_PTR->m_eType = EVT_READY;
  280. if( IM_RESULT *tData = m_fImageAnalyzer( m_oWorkingMat ) ){
  281. //generate detection event
  282. EVT_PTR->m_pEvtData = tData;
  283. } else {
  284. //generate NOT detection event
  285. EVT_PTR->m_pEvtData = NULL;
  286. };
  287. };
  288. m_pActiveJob = NULL;
  289. m_bDataIsActive = false;
  290. };
  291. m_mBufferProtectorMutex.unlock();
  292. };
  293. if( EVT_PTR != NULL ) {
  294. m_pEvtHeap->broadcast( EVT_PTR );
  295. EVT_PTR = NULL;
  296. };
  297. };
  298. };
  299. bool IM_DnnWorker::enqueueJob( IM_JOB *ptr ){
  300. if( ptr ) {
  301. char tPath[1024];
  302. char p1[3];
  303. char p2[3];
  304. char p3[3];
  305. LOG( ptr->md5 );
  306. memcpy( p1, ptr->md5 , 2); p1[2]=(char)0;
  307. memcpy( p2, ptr->md5+2, 2); p2[2]=(char)0;
  308. memcpy( p3, ptr->md5+4, 2); p3[2]=(char)0;
  309. switch( ptr->image_type ) {
  310. case IM_ITEM_TYPE_JPEG: sprintf( tPath, "%s/%s/%s/%s/%s.jpg", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  311. case IM_ITEM_TYPE_PNG: sprintf( tPath, "%s/%s/%s/%s/%s.png", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  312. case IM_ITEM_TYPE_GIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  313. case IM_ITEM_TYPE_AGIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  314. case IM_ITEM_TYPE_AVIF: sprintf( tPath, "%s/%s/%s/%s/%s.avif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  315. case IM_ITEM_TYPE_TIFF: sprintf( tPath, "%s/%s/%s/%s/%s.tiff", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break;
  316. };
  317. #ifdef DEBUG
  318. LOG( tPath );
  319. #endif
  320. Mat Frame = cv::imread( tPath, IMREAD_COLOR );
  321. if( !Frame.empty() ){
  322. while( m_bThreadStatus < TH_ENDED ) {
  323. if( m_mBufferProtectorMutex.try_lock() ) {
  324. Frame.copyTo( m_oWorkingMat );
  325. #ifdef DEBUG
  326. cv::imwrite("cur-test-img.jpg", m_oWorkingMat );
  327. #endif
  328. m_bDataIsActive = true;
  329. m_pActiveJob = ptr;
  330. m_mBufferProtectorMutex.unlock();
  331. return true;
  332. } else SLEEP(5);
  333. };
  334. } else {
  335. LOG_ERROR( "Failure during Image Read!" );
  336. };
  337. };
  338. return false;
  339. };
  340. #undef LOG
  341. #undef LOG_ERROR