cut_point_rs_reid.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. /*
  2. 砧木切割点后识别
  3. */
  4. #include <opencv2\imgproc\imgproc.hpp>
  5. #include <opencv2\features2d\features2d.hpp>
  6. //#include <opencv2\nonfree\features2d.hpp>
  7. #include <math.h>
  8. #include <algorithm>
  9. #include "cut_point_rs_reid.h"
  10. #include "utils.h"
  11. #include "data_def.h"
  12. #include "logger.h"
  13. //using namespace cv;
  14. namespace graft_cv{
  15. CRootStockCutPointReid::CRootStockCutPointReid(ConfigParam&cp,CGcvLogger*pLog/*=0*/)
  16. :m_cparam(cp),
  17. m_pLogger(pLog),
  18. m_pImginfoBinFork(0),
  19. m_pImgCorners(0),
  20. m_pImgCutPoint(0),
  21. m_imgId(""),
  22. m_ppImgSaver(0)
  23. {
  24. }
  25. CRootStockCutPointReid::~CRootStockCutPointReid()
  26. {
  27. this->clear_imginfo();
  28. }
  29. void CRootStockCutPointReid::clear_imginfo(){
  30. if (m_pImginfoBinFork){
  31. imginfo_release(&m_pImginfoBinFork);
  32. m_pImginfoBinFork=0;
  33. }
  34. if (m_pImgCorners){
  35. imginfo_release(&m_pImgCorners);
  36. m_pImgCorners=0;
  37. }
  38. if (m_pImgCutPoint){
  39. imginfo_release(&m_pImgCutPoint);
  40. m_pImgCutPoint=0;
  41. }
  42. }
  43. int CRootStockCutPointReid::cut_point_reid(
  44. ImgInfo* imginfo,
  45. cv::Mat&cimg,
  46. const char * pre_img_id,
  47. PositionInfo& posinfo,
  48. map<string, cv::Mat>& img_cache
  49. )
  50. {
  51. // cimg --- color image, bgr
  52. if(m_pLogger){
  53. m_pLogger->INFO(m_imgId +" rootstock cut_pt reid begin");
  54. }
  55. if(!pre_img_id){
  56. if(m_pLogger){
  57. m_pLogger->ERRORINFO(m_imgId +" pre-image id is NULL");
  58. }
  59. return 1;
  60. }
  61. string pre_imgid(pre_img_id);
  62. map<string, cv::Mat>::iterator iter = img_cache.find(pre_imgid);
  63. if(iter==img_cache.end()){
  64. if(m_pLogger){
  65. m_pLogger->ERRORINFO(m_imgId +" pre-image NOT in cache");
  66. }
  67. return 1;
  68. }
  69. m_preGrayImg = iter->second;
  70. m_imgId = getImgId(img_type::rs_reid);
  71. //1 image segment
  72. clock_t t;
  73. clock_t t0 = clock();
  74. cv::Mat img;
  75. if(imginfo){
  76. if(m_pLogger){
  77. stringstream buff;
  78. buff<<m_imgId<<" rootstock image, width="<<imginfo->width
  79. <<"\theight="<<imginfo->height;
  80. m_pLogger->INFO(buff.str());
  81. }
  82. if(!isvalid(imginfo)){
  83. if(m_pLogger){
  84. m_pLogger->ERRORINFO(m_imgId+" rootstock input image invalid.");
  85. }
  86. throw_msg(m_imgId+" invalid input image");
  87. }
  88. img = imginfo2mat(imginfo);
  89. }
  90. else{
  91. if(m_pLogger){
  92. stringstream buff;
  93. buff<<m_imgId<<"rootstock image, width="<<cimg.cols
  94. <<"\theight="<<cimg.rows;
  95. m_pLogger->INFO(buff.str());
  96. }
  97. if(cimg.empty()){
  98. if(m_pLogger){
  99. m_pLogger->ERRORINFO(m_imgId+" rootstock input image invalid.");
  100. }
  101. throw_msg(m_imgId +" invalid input image");
  102. }
  103. img = cimg;
  104. }
  105. if(m_cparam.self_camera){
  106. image_set_bottom(img,20,8);
  107. if(m_pLogger){
  108. m_pLogger->DEBUG(m_imgId+" image set bottom with pixel value 20.");
  109. }
  110. }
  111. if(m_cparam.rs_y_flip){
  112. flip(img,img,0);
  113. if(m_pLogger){
  114. m_pLogger->DEBUG(m_imgId+" image y fliped.");
  115. }
  116. }
  117. //image saver
  118. if(m_ppImgSaver && *m_ppImgSaver){
  119. (*m_ppImgSaver)->saveImage(img, m_imgId);
  120. }
  121. if(m_pLogger){
  122. m_pLogger->DEBUG(m_imgId+" before image segment.");
  123. }
  124. ///////////////////////////////////////////////////////
  125. // image segment
  126. this->img_preprocess(img);
  127. if(m_pLogger){
  128. m_pLogger->DEBUG(m_imgId+" after image gray.");
  129. }
  130. if(m_cparam.image_show){
  131. cv::destroyAllWindows();
  132. imshow_wait("rs_pre_gray",m_preGrayImg);
  133. imshow_wait("rs_gray",m_grayImg);
  134. }
  135. else{
  136. t = clock();
  137. if(1000.0*((float)(t-t0))/CLOCKS_PER_SEC>(float)m_cparam.timeout_proc){
  138. if(m_pLogger){
  139. m_pLogger->ERRORINFO(m_imgId+" rootstock reid timeout.");
  140. }
  141. throw_msg(m_imgId+" time out");
  142. }
  143. }
  144. if(m_pLogger){
  145. m_pLogger->DEBUG(m_imgId+" after pre- and cur- gray image show.");
  146. }
  147. //特征提取
  148. //int max_feature = 500;
  149. //cv::OrbFeatureDetector fts_detector(max_feature);
  150. ////SurfFeatureDetector fts_detector(max_feature);
  151. //std::vector<cv::KeyPoint> keypoints_pre, keypoints_cur;
  152. //fts_detector.detect( m_preGrayImg, keypoints_pre );
  153. //fts_detector.detect( m_grayImg, keypoints_cur );
  154. //cv::SurfDescriptorExtractor extractor;
  155. //cv::Mat descriptors_pre, descriptors_cur;
  156. //extractor.compute( m_preGrayImg, keypoints_pre, descriptors_pre );
  157. //extractor.compute( m_grayImg, keypoints_cur, descriptors_cur );
  158. ////-- Step 3: Matching descriptor vectors with a brute force matcher
  159. //cv::BFMatcher matcher(cv::NORM_L2);
  160. //std::vector< cv::DMatch > matches;
  161. //cv::matcher.match( descriptors_pre, descriptors_cur, matches );
  162. //if(m_cparam.image_show){
  163. // //-- Draw matches
  164. // cv::Mat img_matches;
  165. // cv::drawMatches( m_preGrayImg, keypoints_pre, m_grayImg, keypoints_cur, matches, img_matches );
  166. // //-- Show detected matches
  167. // cv::imshow("Matches", img_matches );
  168. // cv::waitKey(-1);
  169. //}
  170. posinfo.rs_reid_upoint_x = 10.0;
  171. posinfo.rs_reid_upoint_y = 10.0;
  172. posinfo.rs_reid_lpoint_x = 20.0;
  173. posinfo.rs_reid_lpoint_y = 20.0;
  174. //if(m_pLogger){
  175. // stringstream buff;
  176. // buff<<m_imgId<<" rootstock image, rs_cut_upoint(mm)("<<rs_cut_upoint_x
  177. // <<","<<rs_cut_upoint_y<<")"
  178. // <<", rs_stem_diameter(mm)="<<rs_stem_diameter
  179. // <<", lower_cut_pt(mm)("<<rs_cut_lpoint_x
  180. // <<","<<rs_cut_lpoint_y<<")";
  181. // m_pLogger->INFO(buff.str());
  182. //}
  183. //// return images: posinfo.pp_images
  184. //if(m_cparam.image_return){
  185. // this->clear_imginfo();
  186. // //0) image id
  187. // strcpy(posinfo.rs_img_id,m_imgId.c_str());
  188. // //1)
  189. // //stem x-range
  190. // line(m_binImg,Point(stem_x0,0),Point(stem_x0,m_binImg.cols-1),Scalar(100),2);
  191. // line(m_binImg,Point(stem_x1,0),Point(stem_x1,m_binImg.cols-1),Scalar(100),2);
  192. // //fork right point
  193. // circle(m_binImg, Point(stem_fork_left_x,stem_fork_y),5, Scalar(128,0,128), -1, 8,0);
  194. // m_pImginfoBinFork=mat2imginfo(m_binImg);
  195. // //3 cut point int gray image
  196. // circle(m_grayImg, Point(stem_fork_left_x,stem_fork_y),5, Scalar(128,0,128), -1, 8,0);
  197. // circle(m_grayImg, Point(stem_fork_right_x,stem_fork_y),5, Scalar(128,0,128), -1, 8,0);//v0.5.9.3 reference point
  198. // circle(m_grayImg, Point(cut_pt.x,stem_fork_y),5, Scalar(128,0,128), -1, 8,0);//v0.5.9.3 reference point
  199. // circle(m_grayImg, Point(cut_pt.x,stem_fork_y),2, Scalar(255,0,255), -1, 8,0);
  200. // circle(m_grayImg, Point(lower_cut_pt.x,lower_cut_pt.y),5, Scalar(200,0,200), -1, 8,0);
  201. // image_draw_line(m_grayImg,cut_pt.x,cut_pt.y,lower_cut_pt.x,lower_cut_pt.y);
  202. //
  203. // m_pImgCutPoint = mat2imginfo(m_grayImg);
  204. // posinfo.pp_images[0]=m_pImginfoBinFork;
  205. // posinfo.pp_images[1]=m_pImgCutPoint;
  206. // if(m_ppImgSaver && *m_ppImgSaver){
  207. // (*m_ppImgSaver)->saveImage(m_binImg, m_imgId+"_rst_0");
  208. // (*m_ppImgSaver)->saveImage(m_grayImg, m_imgId+"_rst_1");
  209. // }
  210. //}
  211. if(m_pLogger){
  212. m_pLogger->INFO(m_imgId +" rootstock cut reid detect finished.");
  213. }
  214. return 0;
  215. };
  216. void CRootStockCutPointReid::img_preprocess(cv::Mat&img)
  217. {
  218. //灰度化
  219. cv::Mat b_img;
  220. if(img.channels()!=1){
  221. //color image ,bgr, for testing
  222. cvtColor(img,m_grayImg, cv::COLOR_BGR2GRAY);
  223. }
  224. else{
  225. m_grayImg = img.clone();
  226. }
  227. /*Mat kernel = getStructuringElement(
  228. MORPH_ELLIPSE,
  229. Size( 2*m_cparam.rs_morph_radius + 1, 2*m_cparam.rs_morph_radius+1 ),
  230. Point( m_cparam.rs_morph_radius, m_cparam.rs_morph_radius )
  231. );
  232. double th = threshold(m_grayImg, b_img, 255, 255,THRESH_OTSU);
  233. morphologyEx(
  234. b_img,
  235. m_binImg,
  236. MORPH_CLOSE,
  237. kernel,
  238. Point(-1,-1),
  239. m_cparam.rs_morph_iteration
  240. );*/
  241. }
  242. ///////////////////////////////////////////////////////////////////////////////////////
  243. ///////////////////////////////////////////////////////////////////////////////////////
  244. CSolaCutPointReid::CSolaCutPointReid(ConfigParam&cp, int stemType, CGcvLogger*pLog)
  245. :m_cparam(cp),
  246. m_pLogger(pLog),
  247. m_stem_type(stemType),
  248. m_imgId(""),
  249. m_ppImgSaver(0),
  250. m_pImginfoBin(0),
  251. m_pImgCutPoint(0)
  252. {
  253. }
  254. CSolaCutPointReid::~CSolaCutPointReid()
  255. {}
  256. void CSolaCutPointReid::clear_imginfo() {
  257. if (m_pImginfoBin) {
  258. imginfo_release(&m_pImginfoBin);
  259. m_pImginfoBin = 0;
  260. }
  261. if (m_pImgCutPoint) {
  262. imginfo_release(&m_pImgCutPoint);
  263. m_pImgCutPoint = 0;
  264. }
  265. }
  266. int CSolaCutPointReid::cut_point_reid(
  267. ImgInfo* imginfo,
  268. cv::Mat&cimg,
  269. PositionInfo& posinfo
  270. )
  271. {
  272. if (m_stem_type == 0) {
  273. m_imgId = getImgId(img_type::sola_rs_reid);
  274. }
  275. else {
  276. m_imgId = getImgId(img_type::sola_sc_reid);
  277. }
  278. //1 image segment
  279. clock_t t;
  280. clock_t t0 = clock();
  281. cv::Mat img;
  282. if (imginfo) {
  283. if (m_pLogger) {
  284. stringstream buff;
  285. buff << m_imgId<<" "<<get_stem_type_name() << " image, width=" << imginfo->width
  286. << "\theight=" << imginfo->height;
  287. m_pLogger->INFO(buff.str());
  288. }
  289. if (!isvalid(imginfo)) {
  290. if (m_pLogger) {
  291. m_pLogger->ERRORINFO(m_imgId +string(" ")+get_stem_type_name() + " input image invalid.");
  292. }
  293. throw_msg(m_imgId + string(" ") + get_stem_type_name() + " invalid input image");
  294. }
  295. img = imginfo2mat(imginfo);
  296. }
  297. else {
  298. if (m_pLogger) {
  299. stringstream buff;
  300. buff << m_imgId << " " << get_stem_type_name() << " image, width=" << cimg.cols
  301. << "\theight=" << cimg.rows;
  302. m_pLogger->INFO(buff.str());
  303. }
  304. if (cimg.empty()) {
  305. if (m_pLogger) {
  306. m_pLogger->ERRORINFO(m_imgId +string(" ")+ get_stem_type_name() + " input image invalid.");
  307. }
  308. throw_msg(m_imgId + string(" ") +get_stem_type_name() + " invalid input image");
  309. }
  310. img = cimg;
  311. }
  312. /*if (m_cparam.self_camera) {
  313. image_set_bottom(img, 20, 8);
  314. if (m_pLogger) {
  315. m_pLogger->DEBUG(m_imgId + " image set bottom with pixel value 20.");
  316. }
  317. }*/
  318. if (m_cparam.rs_y_flip) {
  319. flip(img, img, 0);
  320. if (m_pLogger) {
  321. m_pLogger->DEBUG(m_imgId + string(" ") + get_stem_type_name() + " image y fliped.");
  322. }
  323. }
  324. //image saver
  325. if (m_ppImgSaver && *m_ppImgSaver) {
  326. (*m_ppImgSaver)->saveImage(img, m_imgId);
  327. }
  328. if (m_pLogger) {
  329. m_pLogger->DEBUG(m_imgId + string(" ") + get_stem_type_name() + " before image segment.");
  330. }
  331. ///////////////////////////////////////////////////////
  332. // image segment
  333. this->img_preprocess(img);
  334. if (m_pLogger) {
  335. m_pLogger->DEBUG(m_imgId + " after image gray.");
  336. }
  337. if (m_cparam.image_show) {
  338. cv::destroyAllWindows();
  339. imshow_wait("gray", m_grayImg);
  340. imshow_wait("binary", m_binImg);
  341. }
  342. else {
  343. t = clock();
  344. if (1000.0*((float)(t - t0)) / CLOCKS_PER_SEC>(float)m_cparam.timeout_proc) {
  345. if (m_pLogger) {
  346. m_pLogger->ERRORINFO(m_imgId + " rootstock reid timeout.");
  347. }
  348. throw_msg(m_imgId + " time out");
  349. }
  350. }
  351. if (m_pLogger) {
  352. m_pLogger->DEBUG(m_imgId + " after gray image show.");
  353. }
  354. // find object
  355. vector<vector<cv::Point>> contours;
  356. vector<cv::Vec4i> hierarchy;
  357. contours.clear();
  358. hierarchy.clear();
  359. int obj_area_th = 100;//m_cparam
  360. double max_area = 0;
  361. int max_idx = -1;
  362. findContours(m_binImg, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
  363. for (int i = 0; i<contours.size(); ++i) {
  364. double area = contourArea(contours[i]);
  365. if (area < obj_area_th) { continue; }
  366. if(area<max_area) { continue; }
  367. max_area = area;
  368. max_idx = i;
  369. }
  370. if (max_idx < 0 || contours[max_idx].size()==0) {
  371. throw_msg(m_imgId + " no valid object");
  372. }
  373. vector<cv::Point> cut_curve;
  374. cv::RotatedRect retval;
  375. find_cut_curve(contours[max_idx], cut_curve, retval);
  376. if (m_cparam.image_show) {
  377. cv::Mat tmp = m_grayImg.clone();
  378. cv::ellipse(tmp, retval, cv::Scalar(200));
  379. imshow_wait("gray_ellipse", tmp);
  380. }
  381. posinfo.rs_reid_sola_upoint_x = retval.center.x;
  382. posinfo.rs_reid_sola_upoint_y = retval.center.y - retval.size.height / 2;
  383. posinfo.rs_reid_sola_cpoint_x = retval.center.x;
  384. posinfo.rs_reid_sola_cpoint_y = retval.center.y;
  385. posinfo.rs_reid_sola_lpoint_x = retval.center.x;
  386. posinfo.rs_reid_sola_lpoint_y = retval.center.y + retval.size.height/2;
  387. if(m_pLogger){
  388. stringstream buff;
  389. buff<<m_imgId<<" rootstock image, rs_cut_upoint("<< posinfo.rs_reid_sola_upoint_x
  390. <<","<< posinfo.rs_reid_sola_upoint_y <<")"
  391. <<", rs_cut_cpoint=("<< posinfo.rs_reid_sola_cpoint_x
  392. << "," << posinfo.rs_reid_sola_cpoint_y << ")"
  393. <<", rs_cut_lpoint(mm)("<< posinfo.rs_reid_sola_lpoint_x
  394. <<","<< posinfo.rs_reid_sola_lpoint_y <<")";
  395. m_pLogger->INFO(buff.str());
  396. }
  397. // return images: posinfo.pp_images
  398. if(m_cparam.image_return){
  399. this->clear_imginfo();
  400. //0) image id
  401. strcpy(posinfo.rs_img_id,m_imgId.c_str());
  402. //1) bin image
  403. m_pImginfoBin=mat2imginfo(m_binImg);
  404. //2 cut point int gray image
  405. cv::Mat tmp = m_grayImg.clone();
  406. cv::ellipse(tmp, retval, cv::Scalar(200));
  407. m_pImgCutPoint = mat2imginfo(tmp);
  408. posinfo.pp_images[0] = m_pImginfoBin;
  409. posinfo.pp_images[1] = m_pImgCutPoint;
  410. if(m_ppImgSaver && *m_ppImgSaver){
  411. (*m_ppImgSaver)->saveImage(m_binImg, m_imgId+"_rst_0");
  412. (*m_ppImgSaver)->saveImage(tmp, m_imgId+"_rst_1");
  413. }
  414. }
  415. if (m_pLogger) {
  416. m_pLogger->INFO(m_imgId + " rootstock cut reid detect finished.");
  417. }
  418. return 0;
  419. };
  420. void CSolaCutPointReid::find_cut_curve(vector<cv::Point>&curve_points,
  421. vector<cv::Point>&cut_curve, cv::RotatedRect& retval)
  422. {
  423. int max_y = curve_points[0].y;
  424. int min_y = curve_points[0].y;
  425. int max_x = curve_points[0].x;
  426. int min_x = curve_points[0].x;
  427. for (auto&pt : curve_points) {
  428. if (pt.y > max_y) {
  429. max_y = pt.y;
  430. }
  431. if (pt.y < min_y) {
  432. min_y = pt.y;
  433. }
  434. if (pt.x > max_x) {
  435. max_x = pt.x;
  436. }
  437. if (pt.x < min_x) {
  438. min_x = pt.x;
  439. }
  440. }
  441. vector<int>stem_width;
  442. int line_min_x, line_max_x;
  443. for (int y = min_y; y <= max_y;++y) {
  444. line_min_x = max_x;
  445. line_max_x = min_x;
  446. for (auto&pt : curve_points) {
  447. if (pt.y != y) { continue; }
  448. if (pt.x < line_min_x) { line_min_x = pt.x; }
  449. if (pt.x > line_max_x) { line_max_x = pt.x; }
  450. }
  451. stem_width.push_back(line_max_x - line_min_x + 1);
  452. }
  453. // find y range curve
  454. int min_yc = min_y;
  455. int max_yc = max_y;
  456. if (m_stem_type == 0) {
  457. int pos = trend_detect_pos(stem_width, 15);
  458. if (pos > 0) {
  459. max_yc = min_yc + pos;
  460. }
  461. else {
  462. throw(m_imgId + " not found cut curve range");
  463. }
  464. }
  465. else {
  466. vector<int> stem_width_r;
  467. vector<int>::reverse_iterator rit = stem_width.rbegin();
  468. for (; rit != stem_width.rend(); ++rit) {
  469. stem_width_r.push_back(*rit);
  470. }
  471. int pos = trend_detect_pos(stem_width_r, 15);
  472. if (pos > 0) {
  473. min_yc = max_yc - pos;
  474. }
  475. else {
  476. throw(m_imgId + " not found cut curve range");
  477. }
  478. }
  479. // copy cut curve points
  480. vector<cv::Point>cut_curve_points;
  481. for (auto&pt : curve_points) {
  482. if (pt.y >= min_yc && pt.y <= max_yc) {
  483. cut_curve_points.push_back(cv::Point(pt));
  484. }
  485. }
  486. // ecllipse fit
  487. retval = cv::fitEllipse(cut_curve_points);
  488. //if (m_cparam.image_show) {
  489. // //cv::destroyAllWindows();
  490. // cv::Mat tmp = m_grayImg.clone();
  491. // for (auto&pt : cut_curve_points) {
  492. // tmp.at<cv::uint8_t>(pt.y, pt.x+500) = 200;
  493. // }
  494. // //cv::ellipse(tmp, retval, cv::Scalar(200));
  495. // imshow_wait("cut_curve", tmp);
  496. //}
  497. }
  498. string CSolaCutPointReid::get_stem_type_name() {
  499. if (m_stem_type == 0) {
  500. return string("solanaceae rootstock");
  501. }
  502. else {
  503. return string("solanaceae scion");
  504. }
  505. }
  506. void CSolaCutPointReid::img_preprocess(cv::Mat&img)
  507. {
  508. //灰度化
  509. cv::Mat b_img;
  510. if (img.channels() != 1) {
  511. //color image ,bgr, for testing
  512. cvtColor(img, m_grayImg, cv::COLOR_BGR2GRAY);
  513. }
  514. else {
  515. m_grayImg = img.clone();
  516. }
  517. cv::Mat kernel = cv::getStructuringElement(
  518. cv::MORPH_ELLIPSE,
  519. cv::Size(5, 5),
  520. cv::Point(2,2)
  521. );
  522. double th = threshold(m_grayImg, b_img, 255, 255, cv::THRESH_OTSU);
  523. morphologyEx(
  524. b_img,
  525. m_binImg,
  526. cv::MORPH_CLOSE,
  527. kernel,
  528. cv::Point(-1, -1),
  529. 2
  530. );
  531. }
  532. }