grab_point_rs.cpp 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426
  1. /*
  2. 通过点云数据识别抓取位置信息
  3. 1)获取点云
  4. 2)剔除离群点
  5. 3)降采样
  6. 4)植株检测
  7. 5)选出最前,最右侧植株
  8. 6)植株抓取位置检测
  9. */
  10. #include <algorithm>
  11. #include <pcl\io\ply_io.h>
  12. #include <pcl\visualization\cloud_viewer.h>
  13. #include <pcl\filters\crop_box.h>
  14. #include <pcl\filters\radius_outlier_removal.h>
  15. #include <pcl\filters\statistical_outlier_removal.h>
  16. #include <pcl\filters\voxel_grid.h>
  17. #include <pcl\common\common.h>
  18. #include <pcl\features\moment_of_inertia_estimation.h>
  19. #include <pcl\segmentation\sac_segmentation.h>
  20. #include <pcl\segmentation\extract_clusters.h>
  21. #include <math.h>
  22. #include <pcl\features\normal_3d.h>
  23. #include <pcl\features\boundary.h>
  24. #include "grab_point_rs.h"
  25. #include "utils.h"
  26. #include "peak_finder.h"
  27. #define PI std::acos(-1)
  28. namespace graft_cv {
  29. CRootStockGrabPoint::CRootStockGrabPoint(ConfigParam&cp, CGcvLogger*pLog/*=0*/)
  30. :m_cparam(cp),
  31. m_pLogger(pLog),
  32. m_dtype(0),
  33. m_pcdId(""),
  34. m_ppImgSaver(0),
  35. m_1st_row_zmean_rs(-1.0),
  36. m_1st_row_zmean_sc(-1.0),
  37. m_cloud_mean_dist(0.0),
  38. m_pImginfoResult(0),
  39. m_pStemInfos(0),
  40. m_pSeedlingStatus(0)
  41. {
  42. }
  43. void CRootStockGrabPoint::clear_imginfo() {
  44. if (m_pImginfoResult) {
  45. imginfo_release(&m_pImginfoResult);
  46. m_pImginfoResult = 0;
  47. }
  48. }
  49. CRootStockGrabPoint::~CRootStockGrabPoint() {
  50. this->clear_imginfo();
  51. if (m_pStemInfos) {
  52. delete m_pStemInfos;
  53. m_pStemInfos = 0;
  54. }
  55. if (m_pSeedlingStatus) {
  56. delete m_pSeedlingStatus;
  57. m_pSeedlingStatus = 0;
  58. }
  59. }
  60. float* CRootStockGrabPoint::get_raw_point_cloud(int &data_size)
  61. {
  62. data_size = m_raw_cloud->width * m_raw_cloud->height;
  63. if (data_size == 0) {
  64. return 0;
  65. }
  66. else {
  67. pcl::PointXYZ* pp = m_raw_cloud->points.data();
  68. return (float*)pp->data;
  69. }
  70. }
  71. int CRootStockGrabPoint::load_data(
  72. float*pPoint,
  73. int pixel_size,
  74. int pt_size,
  75. int dtype,
  76. const char* fn/* = 0*/)
  77. {
  78. //数据加载功能实现,并生成imageid,保存原始数据到文件
  79. int rst = 0;
  80. m_dtype = dtype;
  81. //generate image id
  82. if (m_dtype == 0) {
  83. m_pcdId = getImgId(img_type::sola_sc_pcd);
  84. }
  85. else {
  86. m_pcdId = getImgId(img_type::sola_rs_pcd);
  87. }
  88. //1 get point cloud data
  89. if (pPoint != 0 && pt_size>0) {
  90. //read point
  91. m_raw_cloud.reset(new pcl::PointCloud<pcl::PointXYZ>);
  92. int step = pixel_size;
  93. for (int i = 0; i < pt_size; ++i) {
  94. pcl::PointXYZ pt = { pPoint[i*step], pPoint[i*step + 1] , pPoint[i*step + 2] };
  95. m_raw_cloud->push_back(pt);
  96. }
  97. rst = m_raw_cloud->width * m_raw_cloud->height;
  98. if (m_pLogger) {
  99. stringstream buff;
  100. buff << m_pcdId <<": load raw point cloud " << rst << " data points";
  101. m_pLogger->INFO(buff.str());
  102. }
  103. }
  104. else if (fn != 0) {
  105. //read file
  106. rst = this->read_ply_file(fn);
  107. }
  108. else {//error
  109. if (m_pLogger) {
  110. m_pLogger->ERRORINFO(m_pcdId + ": no valid input");
  111. return (-1);
  112. }
  113. }
  114. if (m_ppImgSaver && *m_ppImgSaver) {
  115. (*m_ppImgSaver)->saveBinPly(m_raw_cloud, m_pcdId);
  116. }
  117. if (m_cparam.image_show) {
  118. pcl::visualization::PCLVisualizer viewer(m_pcdId + std::string(": raw point cloud"));
  119. viewer.setBackgroundColor(0.35, 0.35, 0.35);
  120. viewer.addCoordinateSystem();
  121. viewer.addPointCloud<pcl::PointXYZ>(m_raw_cloud, "raw_cloud");
  122. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "raw_cloud");
  123. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "raw_cloud");
  124. float xmin, ymin, zmin, xmax, ymax, zmax;
  125. xmin = m_cparam.rs_grab_xmin;
  126. ymin = m_cparam.rs_grab_ymin;
  127. zmin = m_cparam.rs_grab_zmin;
  128. xmax = m_cparam.rs_grab_xmax;
  129. ymax = m_cparam.rs_grab_ymax;
  130. zmax = m_cparam.rs_grab_zmax;
  131. if (m_dtype == 0) {
  132. xmin = m_cparam.sc_grab_xmin;
  133. ymin = m_cparam.sc_grab_ymin;
  134. zmin = m_cparam.sc_grab_zmin;
  135. xmax = m_cparam.sc_grab_xmax;
  136. ymax = m_cparam.sc_grab_ymax;
  137. zmax = m_cparam.sc_grab_zmax;
  138. }
  139. viewer.addCube(xmin, xmax,ymin, ymax, zmin, zmax, 0.75, 0.0, 0.0, "AABB_");
  140. viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION,
  141. pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "AABB_");
  142. pcl::PointXYZ px0, px1, py1, pz1;
  143. px0.x = 0;
  144. px0.y = 0;
  145. px0.z = 0;
  146. px1.x = 10.0;
  147. px1.y = 0;
  148. px1.z = 0;
  149. py1.x = 0;
  150. py1.y = 10.0;
  151. py1.z = 0;
  152. pz1.x = 0;
  153. pz1.y = 0;
  154. pz1.z = 10.0;
  155. viewer.addLine(px0, px1, 255, 0, 0, "x");
  156. viewer.addLine(px0, py1, 0, 255, 0, "y");
  157. viewer.addLine(px0, pz1, 0, 0, 255, "z");
  158. while (!viewer.wasStopped()) {
  159. viewer.spinOnce(100);
  160. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  161. }
  162. }
  163. if (m_pStemInfos==0) {
  164. double seedling_distance = m_cparam.rs_grab_seedling_dist;
  165. int holes_number = m_cparam.rs_grab_holes_number;
  166. double x_min = m_cparam.rs_grab_xmin;
  167. double x_max = m_cparam.rs_grab_xmax;
  168. double z_min = m_cparam.rs_grab_zmin;
  169. double z_max = m_cparam.rs_grab_zmax;
  170. if (m_dtype == 0) {
  171. seedling_distance = m_cparam.sc_grab_seedling_dist;
  172. holes_number = m_cparam.sc_grab_holes_number;
  173. x_min = m_cparam.sc_grab_xmin;
  174. x_max = m_cparam.sc_grab_xmax;
  175. z_min = m_cparam.sc_grab_zmin;
  176. z_max = m_cparam.sc_grab_zmax;
  177. }
  178. m_pStemInfos = new CStemResultInfos(
  179. seedling_distance, holes_number,
  180. x_min, x_max, z_min, z_max,
  181. m_pcdId, m_pLogger);
  182. }
  183. return rst;
  184. }
  185. int CRootStockGrabPoint::grab_point_detect(
  186. PositionInfo& posinfo
  187. )
  188. {
  189. // 抓取位置识别入口函数,实现整个抓取位置识别功能,返回抓取位置信息
  190. // dtype == 0, scion
  191. // dtype != 0, rootstock
  192. // 输入,穗苗--0, 砧木--1
  193. if (m_raw_cloud->width * m_raw_cloud->height < 1) {
  194. if (m_pLogger) {
  195. stringstream buff;
  196. buff << m_pcdId << ": m_raw_cloud point cloud " << m_raw_cloud->width * m_raw_cloud->height << " data points";
  197. m_pLogger->ERRORINFO(buff.str());
  198. }
  199. return 1;
  200. }
  201. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  202. //1 crop filter,剪裁需要的部分点云
  203. if (m_pLogger) {
  204. m_pLogger->INFO(m_pcdId + ": begin crop");
  205. }
  206. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  207. pcl::CropBox<pcl::PointXYZ> box_filter;
  208. if (m_dtype != 0) {//rootstock
  209. box_filter.setMin(Eigen::Vector4f(m_cparam.rs_grab_xmin, m_cparam.rs_grab_ymin, m_cparam.rs_grab_zmin, 1));
  210. box_filter.setMax(Eigen::Vector4f(m_cparam.rs_grab_xmax, m_cparam.rs_grab_ymax, m_cparam.rs_grab_zmax, 1));
  211. }
  212. else {//scion
  213. box_filter.setMin(Eigen::Vector4f(m_cparam.sc_grab_xmin, m_cparam.sc_grab_ymin, m_cparam.sc_grab_zmin, 1));
  214. box_filter.setMax(Eigen::Vector4f(m_cparam.sc_grab_xmax, m_cparam.sc_grab_ymax, m_cparam.sc_grab_zmax, 1));
  215. }
  216. box_filter.setNegative(false);
  217. box_filter.setInputCloud(m_raw_cloud);
  218. box_filter.filter(*cloud_inbox);
  219. if (m_pLogger) {
  220. stringstream buff;
  221. buff << m_pcdId << ": CropBox croped point cloud " << cloud_inbox->width * cloud_inbox->height << " data points";
  222. m_pLogger->INFO(buff.str());
  223. }
  224. if (cloud_inbox->width * cloud_inbox->height < 1) {
  225. return 1;
  226. }
  227. if (m_cparam.image_show) {
  228. viewer_cloud(cloud_inbox, std::string("cloud_inbox"));
  229. }
  230. if (m_pLogger) {
  231. m_pLogger->INFO(m_pcdId + ": end crop");
  232. }
  233. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  234. //2 filtler with radius remove, 去除孤立点
  235. if (m_pLogger) {
  236. m_pLogger->INFO(m_pcdId + ": begin ror");
  237. }
  238. int nb_points = 20;
  239. double stem_radius = m_cparam.rs_grab_stem_diameter / 2.0;
  240. if(m_dtype == 0){
  241. stem_radius = m_cparam.sc_grab_stem_diameter / 2.0;
  242. }
  243. double remove_radius = stem_radius * 2.0;
  244. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_ror(new pcl::PointCloud<pcl::PointXYZ>);
  245. pcl::RadiusOutlierRemoval<pcl::PointXYZ> ror(false);
  246. ror.setInputCloud(cloud_inbox);
  247. ror.setRadiusSearch(remove_radius);
  248. ror.setMinNeighborsInRadius(nb_points);
  249. ror.filter(*cloud_ror);
  250. if (m_pLogger) {
  251. stringstream buff;
  252. buff << m_pcdId <<": RadiusOutlierRemoval filtered point cloud "
  253. << cloud_ror->width * cloud_ror->height
  254. << " data points. param stem_radius="<<
  255. stem_radius<<", nb_points="<< nb_points<< "(if < 50, return)";
  256. m_pLogger->INFO(buff.str());
  257. }
  258. if (cloud_ror->width * cloud_ror->height < 50) {
  259. return 1;
  260. }
  261. if (m_cparam.image_show) {
  262. viewer_cloud(cloud_ror, std::string("cloud_ror"));
  263. }
  264. if (m_pLogger) {
  265. m_pLogger->INFO(m_pcdId + ": end ror");
  266. }
  267. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  268. //?? 用截取到的点云,初步找到植株的位置中心
  269. m_root_centers.clear();
  270. m_root_center_with_seedling.clear();
  271. if (m_pStemInfos) {
  272. m_pStemInfos->get_root_centers(m_root_centers);
  273. if (m_pLogger) {
  274. stringstream buff;
  275. buff << m_pcdId << ": root positions "<< m_root_centers.size()<<" centers\n";
  276. for (auto& sr : m_root_centers) {
  277. buff << "\tx=" << sr.root_x << ", y=" << sr.root_y << ", z=" << sr.root_z
  278. << ", cnt=" << sr.root_count
  279. << ", pcd_size=" << sr.stem_size << "\n";
  280. }
  281. m_pLogger->INFO(buff.str());
  282. }
  283. }
  284. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  285. //3 原来的降采样没有意义,改成统计平均距离
  286. m_cloud_mean_dist = 0.0;
  287. cloud_mean_dist(cloud_ror, m_cloud_mean_dist);
  288. if (m_pLogger) {
  289. stringstream buff;
  290. buff << m_pcdId <<": cloud_mean_dist = " << m_cloud_mean_dist;
  291. m_pLogger->INFO(buff.str());
  292. }
  293. if (m_pSeedlingStatus == 0) {
  294. double x_min = m_cparam.rs_grab_xmin;
  295. double x_max = m_cparam.rs_grab_xmax;
  296. if (m_dtype == 0) {
  297. x_min = m_cparam.sc_grab_xmin;
  298. x_max = m_cparam.sc_grab_xmax;
  299. }
  300. m_pSeedlingStatus = new CSeedlingStatus(m_dtype, 5.0, x_min, x_max, m_cloud_mean_dist, m_pLogger);
  301. std::vector<double>root_cxs;
  302. for (auto&sr : m_root_centers) {
  303. root_cxs.push_back(sr.root_x);
  304. }
  305. m_pSeedlingStatus->set_x_centers(root_cxs);
  306. }
  307. /*std::vector<int> center_counts;
  308. std::vector<Eigen::Vector4f> centroids;
  309. get_point_centriod(m_root_centers, center_counts, centroids);*/
  310. std::vector<int>xhist_inbox;
  311. get_point_x_hist(xhist_inbox);
  312. m_pSeedlingStatus->append_hist(xhist_inbox);
  313. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  314. // 4 对截取的点云进行ror滤除大面积联通区域,剔除叶片
  315. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_dowm_sampled(new pcl::PointCloud<pcl::PointXYZ>);
  316. std::vector<int> non_leaf_indices;
  317. std::vector<int> leaf_indices;
  318. leaf_filter_ror(cloud_ror, non_leaf_indices, leaf_indices);
  319. pcl::copyPointCloud(*cloud_ror, non_leaf_indices, *cloud_dowm_sampled);
  320. if (m_pLogger) {
  321. stringstream buff;
  322. buff << m_pcdId << ": after leaf_filter dowm_sampled point cloud "
  323. << cloud_dowm_sampled->width * cloud_dowm_sampled->height << " data points (if < 50, return)";
  324. m_pLogger->INFO(buff.str());
  325. }
  326. if (cloud_dowm_sampled->width * cloud_dowm_sampled->height < 50) {
  327. return 1;
  328. }
  329. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  330. //判断m_root_centers位置上是否有叶片遮挡
  331. occluded_seedling_detect_by_leaf(cloud_ror, leaf_indices);
  332. if (m_pLogger) {
  333. stringstream buff;
  334. buff << m_pcdId << ": leafoccl status: ";
  335. for (auto&st : m_root_center_with_occlusion) {
  336. buff <<st<< "\t";
  337. }
  338. m_pLogger->INFO(buff.str());
  339. }
  340. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  341. //5 seedling position,找到第一个位置上的植株
  342. std::vector<int> first_seedling_cloud_idx; //存储找到的第一个位置上植株茎上直线点的index
  343. pcl::PointXYZ xz_center; //存储找到的第一个位置上植株根部坐标
  344. pcl::ModelCoefficients::Ptr line_model; //存储找到的第一个位置上植株茎直线模型
  345. if (m_pLogger) {
  346. m_pLogger->INFO(m_pcdId + ": begin find seedling position");
  347. }
  348. int first_row_seedling_number = 0;
  349. bool fund_seedling = find_seedling_position_key(cloud_dowm_sampled, first_seedling_cloud_idx, xz_center, line_model, first_row_seedling_number);
  350. if (!fund_seedling && first_row_seedling_number == 0) {
  351. if (m_pLogger) {
  352. stringstream buff;
  353. buff << m_pcdId << ": Not found seedlings" ;
  354. m_pLogger->INFO(buff.str());
  355. }
  356. return 1;
  357. }
  358. if (m_pLogger) {
  359. stringstream buff;
  360. buff << m_pcdId <<": after find_seedling_position(), foud first seedling seeds points size " << first_seedling_cloud_idx.size();
  361. m_pLogger->INFO(buff.str());
  362. m_pLogger->INFO(m_pcdId + ": end find seedling position");
  363. }
  364. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  365. //5.1 如果没有找到茎,在root_center 中找一个位置
  366. pcl::PointXYZ fork_selected_pt;//抓取点坐标,根据茎节点的偏移
  367. pcl::PointXYZ fork_selected_pt_ref; //返回茎节点,作为抓取点偏的基点
  368. pcl::PointXYZ rs_grab_pt; //v0.8.8修改砧木抓取位置为固定高度,通过yup和ybt均值确定
  369. std::vector<float>fork_ys;
  370. if (!fund_seedling) {
  371. int selected_center_idx;
  372. no_seedling_detected_post_process(
  373. first_row_seedling_number, //input
  374. selected_center_idx, //output
  375. fork_selected_pt, //output
  376. fork_selected_pt_ref, //output
  377. rs_grab_pt, //output
  378. posinfo);
  379. if (selected_center_idx < 0) {
  380. if (m_pLogger) {
  381. stringstream buff;
  382. buff << m_pcdId << ": Not found seedlings after no_seedling_detected_post_process()";
  383. m_pLogger->INFO(buff.str());
  384. }
  385. return 1;
  386. }
  387. }
  388. else {
  389. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  390. //6 nearest seedling grab point selection,找到最接近指定高度的最优抓取点坐标
  391. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_seedling_seed(new pcl::PointCloud<pcl::PointXYZ>);
  392. pcl::copyPointCloud(*cloud_dowm_sampled, first_seedling_cloud_idx, *cloud_seedling_seed);
  393. //改进思路:将茎直线上cloud_seedling_seed的点,提取周围邻域xz的宽度,在相同邻域cloud_dowm_sampled点云内提取xz的宽度
  394. //对比两个宽度,变化很大的,说明周边有异物(叶柄或叶子),不适合作为抓取位置;否则就是抓取位置
  395. //在众多抓取位置上,选择离指定高度最近的点作为抓取位置
  396. //
  397. //显示位置
  398. if (m_cparam.image_show) {
  399. std::vector<pcl::PointXYZ> tmp;
  400. tmp.push_back(xz_center);
  401. pcl::PointCloud<pcl::PointXYZRGB>::Ptr tttp(new pcl::PointCloud<pcl::PointXYZRGB>);
  402. pcl::copyPointCloud(*cloud_seedling_seed, *tttp);
  403. for (auto& pt : *tttp) {
  404. pt.r = 255;
  405. pt.g = 255;
  406. pt.b = 255;
  407. }
  408. viewer_cloud_cluster(tttp, tmp, string("first"));
  409. }
  410. float stem_width_mu;
  411. float stem_deflection;
  412. get_optimal_seed_compare(
  413. cloud_dowm_sampled, //input
  414. cloud_seedling_seed, //input
  415. line_model, //input
  416. fork_selected_pt, //output
  417. fork_selected_pt_ref, //output
  418. rs_grab_pt, //output
  419. fork_ys, // 返回,fork y的高度
  420. stem_width_mu, //output
  421. stem_deflection //output
  422. ); //output
  423. if (m_dtype==0 && fork_selected_pt.z < 0) {
  424. int selected_center_idx;
  425. no_seedling_detected_post_process(
  426. first_row_seedling_number, //input
  427. selected_center_idx, //output
  428. fork_selected_pt, //output
  429. fork_selected_pt_ref, //output
  430. rs_grab_pt, //output
  431. posinfo);
  432. if (selected_center_idx < 0) {
  433. if (m_pLogger) {
  434. stringstream buff;
  435. buff << m_pcdId << ": Not found valid fork point after no_seedling_detected_post_process()";
  436. m_pLogger->INFO(buff.str());
  437. }
  438. return 1;
  439. }
  440. }
  441. else {
  442. int selected_center_idx;
  443. had_seedling_detected_post_process(
  444. first_row_seedling_number, //input
  445. stem_width_mu, //input
  446. stem_deflection, //input
  447. selected_center_idx, //output, 选择root_center的序号
  448. fork_selected_pt, //input-output, 检测到的目标抓取点
  449. fork_selected_pt_ref, //input-output, 检测到的目标抓取参考点
  450. rs_grab_pt,
  451. fork_ys,
  452. posinfo);
  453. }
  454. if (m_pLogger) {
  455. m_pLogger->INFO(m_pcdId + ": end get_optimal_seed");
  456. }
  457. }
  458. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  459. //7 保存处理结果到图片
  460. cv::Mat rst_img = cv::Mat::zeros(cv::Size(1280,640),CV_8UC3);
  461. gen_result_img(cloud_ror, cloud_dowm_sampled, fork_selected_pt, fork_selected_pt_ref, rs_grab_pt, fork_ys, posinfo,rst_img);
  462. if (m_ppImgSaver && *m_ppImgSaver) {
  463. (*m_ppImgSaver)->saveImage(rst_img, m_pcdId + "_rst_0");
  464. }
  465. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  466. //8 页面显示结果
  467. m_pImginfoResult = mat2imginfo(rst_img, &m_pImginfoResult);
  468. posinfo.pp_images[0] = m_pImginfoResult;
  469. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  470. //9 debug 显示结果
  471. if (m_cparam.image_show) {
  472. pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_cand_demo(new pcl::PointCloud<pcl::PointXYZRGB>);
  473. pcl::copyPointCloud(*cloud_dowm_sampled, *cloud_cand_demo);
  474. for (auto& pt : *cloud_cand_demo) {
  475. pt.r = 255;
  476. pt.g = 255;
  477. pt.b = 255;
  478. }
  479. if (m_dtype == 0) {
  480. pcl::PointXYZRGB pt_grab = { 0,255,0 };
  481. pt_grab.x = fork_selected_pt.x;
  482. pt_grab.y = fork_selected_pt.y;
  483. pt_grab.z = fork_selected_pt.z;
  484. pcl::PointXYZRGB pt_grab_ = { 0,255,120 };
  485. pt_grab_.x = fork_selected_pt.x;
  486. pt_grab_.y = fork_selected_pt.y + 0.2;
  487. pt_grab_.z = fork_selected_pt.z;
  488. cloud_cand_demo->push_back(pt_grab);
  489. //viewer_cloud(cloud_cand_demo, std::string("cloud_cand_demo"));
  490. viewer_cloud_debug(cloud_cand_demo, fork_selected_pt, fork_selected_pt_ref, xz_center, std::string("cloud_cand_demo"));
  491. }
  492. else {
  493. pcl::PointXYZRGB pt_grab = { 0,255,0 };
  494. pt_grab.x = rs_grab_pt.x;
  495. pt_grab.y = rs_grab_pt.y;
  496. pt_grab.z = rs_grab_pt.z;
  497. pcl::PointXYZRGB pt_grab_ = { 0,255,120 };
  498. pt_grab_.x = rs_grab_pt.x;
  499. pt_grab_.y = rs_grab_pt.y + 0.2;
  500. pt_grab_.z = rs_grab_pt.z;
  501. cloud_cand_demo->push_back(pt_grab);
  502. //viewer_cloud(cloud_cand_demo, std::string("cloud_cand_demo"));
  503. viewer_cloud_debug(cloud_cand_demo, rs_grab_pt, rs_grab_pt, xz_center, std::string("cloud_cand_demo"));
  504. }
  505. imshow_wait("rst_img", rst_img);
  506. }
  507. return 0;
  508. }
  509. //没有检测到苗的后处理
  510. void CRootStockGrabPoint::no_seedling_detected_post_process(
  511. int first_row_seedling_number, //input
  512. int& selected_idx, //output, 选择root_center的序号
  513. pcl::PointXYZ& selected_pt, //output
  514. pcl::PointXYZ& selected_pt_ref, //output
  515. pcl::PointXYZ& rs_grab_pt, //output
  516. PositionInfo& posinfo //output
  517. )
  518. {
  519. selected_pt.x = -1000.0;
  520. selected_pt.y = -1000.0;
  521. selected_pt.z = -1000.0;
  522. selected_pt_ref.x = -1000.0;
  523. selected_pt_ref.y = -1000.0;
  524. selected_pt_ref.z = -1000.0;
  525. rs_grab_pt.x = -1000.0;
  526. rs_grab_pt.y = -1000.0;
  527. rs_grab_pt.z = -1000.0;
  528. //m_dtype == 0 找最大x位置, 否则找最小x位置
  529. selected_idx = -1;
  530. if (m_dtype == 0) {
  531. for (int i = 0; i < m_root_center_with_seedling.size(); ++i) {
  532. if (m_root_center_with_seedling[i]>0) { selected_idx = i; }
  533. }
  534. }
  535. else {
  536. for (int i = 0; i < m_root_center_with_seedling.size(); ++i) {
  537. if (m_root_center_with_seedling[i]>0) {
  538. selected_idx = i;
  539. break;
  540. }
  541. }
  542. }
  543. if (selected_idx < 0) {
  544. return;
  545. }
  546. double grab_fork_ybt = m_cparam.rs_grab_fork_ybt;
  547. double grab_offset = m_cparam.rs_grab_offset;
  548. double grab_seedling_dist = m_cparam.rs_grab_seedling_dist;
  549. double ymin = m_cparam.rs_grab_ymin;
  550. if (m_dtype == 0) {
  551. grab_fork_ybt = m_cparam.sc_grab_fork_ybt;
  552. grab_offset = m_cparam.sc_grab_offset_bt;
  553. grab_seedling_dist = m_cparam.sc_grab_seedling_dist;
  554. ymin = m_cparam.sc_grab_ymin;
  555. }
  556. //cx位置, 默认选择穴位中心,如果leaf中心有值,用叶子中心
  557. double cx = m_root_centers.at(selected_idx).root_x;
  558. double leaf_cx = m_root_center_leaf_cx.at(selected_idx);
  559. if (fabs(leaf_cx - cx) < grab_seedling_dist*0.33) {
  560. cx = leaf_cx;
  561. }
  562. double stem_width_mu = 0.0;
  563. double stem_deflection = 0.0;
  564. if (m_dtype == 0) {
  565. selected_pt_ref.x = cx;
  566. selected_pt_ref.y = ymin;
  567. selected_pt_ref.z = m_root_centers.at(selected_idx).root_z;
  568. selected_pt = selected_pt_ref;
  569. selected_pt.y += static_cast<int>(grab_offset);
  570. posinfo.sc_grab_x = selected_pt.x;
  571. posinfo.sc_grab_y = selected_pt.y;
  572. posinfo.sc_grab_z = selected_pt.z;
  573. posinfo.sc_count = (double)first_row_seedling_number;
  574. posinfo.sc_width = (double)stem_width_mu;
  575. posinfo.sc_tortuosity = (double)stem_deflection;
  576. }
  577. else {
  578. //砧木指定y高度上的确定位置
  579. float grab_y = 0.5 * (m_cparam.rs_grab_fork_ybt + m_cparam.rs_grab_fork_yup);
  580. rs_grab_pt.x = cx;
  581. rs_grab_pt.y = grab_y;
  582. rs_grab_pt.z = m_root_centers.at(selected_idx).root_z;
  583. posinfo.rs_grab_x = rs_grab_pt.x;
  584. posinfo.rs_grab_y = rs_grab_pt.y;
  585. posinfo.rs_grab_z = rs_grab_pt.z;
  586. posinfo.rs_fork_y1 = -1000.0;
  587. posinfo.rs_fork_y2 = -1000.0;
  588. posinfo.rs_fork_y3 = -1000.0;
  589. posinfo.rs_count = (double)first_row_seedling_number;
  590. posinfo.rs_width = (double)stem_width_mu;
  591. posinfo.rs_tortuosity = (double)stem_deflection;
  592. }
  593. }
  594. //检测到苗的情况,后处理
  595. void CRootStockGrabPoint::had_seedling_detected_post_process(
  596. int first_row_seedling_number, //input
  597. float stem_width_mu, //input
  598. float stem_deflection, //input
  599. int& selected_idx, //output, 选择root_center的序号
  600. pcl::PointXYZ& selected_pt, //input-output, 检测到的基于茎节抓取点
  601. pcl::PointXYZ& selected_pt_ref, //input-output, 检测到的茎节点
  602. pcl::PointXYZ& rs_grab_pt, //input-output, 检测到的目标抓取点
  603. std::vector<float>& fork_ys,
  604. PositionInfo& posinfo //output
  605. )
  606. {
  607. //通过selected_pt找到对应的gen中心位置
  608. //0 首选识别到的位置
  609. if (m_dtype == 0) {
  610. posinfo.sc_grab_x = selected_pt.x;
  611. posinfo.sc_grab_y = selected_pt.y;
  612. posinfo.sc_grab_z = selected_pt.z;
  613. posinfo.sc_count = (double)first_row_seedling_number;
  614. posinfo.sc_width = (double)stem_width_mu;
  615. posinfo.sc_tortuosity = (double)stem_deflection;
  616. }
  617. else {
  618. posinfo.rs_grab_x = rs_grab_pt.x;
  619. posinfo.rs_grab_y = rs_grab_pt.y;
  620. posinfo.rs_grab_z = rs_grab_pt.z;
  621. posinfo.rs_fork_y1 = -1000.0;
  622. posinfo.rs_fork_y2 = -1000.0;
  623. posinfo.rs_fork_y3 = -1000.0;
  624. int fsize = fork_ys.size();
  625. if (fsize > 3) { fsize = 3; }
  626. if (fsize == 1) {
  627. posinfo.rs_fork_y1 = fork_ys.at(0);
  628. }
  629. if (fsize == 2) {
  630. posinfo.rs_fork_y1 = fork_ys.at(0);
  631. posinfo.rs_fork_y2 = fork_ys.at(1);
  632. }
  633. if (fsize == 3) {
  634. posinfo.rs_fork_y1 = fork_ys.at(0);
  635. posinfo.rs_fork_y2 = fork_ys.at(1);
  636. posinfo.rs_fork_y3 = fork_ys.at(2);
  637. }
  638. posinfo.rs_count = (double)first_row_seedling_number;
  639. posinfo.rs_width = (double)stem_width_mu;
  640. posinfo.rs_tortuosity = (double)stem_deflection;
  641. }
  642. }
  643. //根据历史根的位置,计算对应位置点云数量,进而判断此位置是否有苗
  644. void CRootStockGrabPoint::occluded_seedling_detect_by_leaf(
  645. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //input 输入点云数据
  646. std::vector<int>& leaf_idx
  647. )
  648. {
  649. //仅用叶子点云数量,有时会出现因叶子误识别(和ror_ratio相关),造成叶子点云数量小,造成误判
  650. //所以改成整个空间点云数量做判别--2024-3-2
  651. m_root_center_with_occlusion.clear();
  652. m_root_center_with_occlusion.assign(m_root_centers.size(), 0);
  653. m_root_center_leaf_cx.clear();
  654. m_root_center_leaf_cx.assign(m_root_centers.size(), 1.0e6);
  655. std::vector<int> pcd_cnt;
  656. //int th_pcd_size = m_cparam.rs_grab_seedling_min_pts;
  657. double stem_diameter = m_cparam.rs_grab_stem_diameter;
  658. double y_min = m_cparam.rs_grab_ymin;
  659. double y_max = m_cparam.rs_grab_ymax;
  660. if (m_dtype == 0) {
  661. //th_pcd_size = m_cparam.sc_grab_seedling_min_pts;
  662. stem_diameter = m_cparam.sc_grab_stem_diameter;
  663. y_min = m_cparam.sc_grab_ymin;
  664. y_max = m_cparam.sc_grab_ymax;
  665. }
  666. int th_pcd_size = int(0.333 * stem_diameter * (y_max - y_min) / m_cloud_mean_dist / m_cloud_mean_dist);
  667. std::vector<pcl::PointXYZ> aabb_mins_maxs;
  668. int total_cnt, leaf_cnt; //穴位上inbox的点云数量,叶子点云数量
  669. double total_cx, leaf_cx;//穴位上inbox的点云中位x,叶子点云中位x
  670. for (int i = 0; i < m_root_centers.size(); ++i) {
  671. CStemResult& rc = m_root_centers.at(i);
  672. pcl::PointXYZ aabb_min;
  673. pcl::PointXYZ aabb_max;
  674. get_leaf_point_count_inbox(rc, in_cloud, leaf_idx,
  675. aabb_min, aabb_max,
  676. total_cnt, leaf_cnt,
  677. total_cx, leaf_cx);
  678. double leaf_ratio = 0.0;
  679. if (total_cnt == 0) {
  680. leaf_ratio = 0.0;
  681. }
  682. else {
  683. leaf_ratio = double(leaf_cnt) / double(total_cnt);
  684. }
  685. if (leaf_ratio > 0.25) {
  686. m_root_center_leaf_cx.at(i) = leaf_cx;
  687. }
  688. else {
  689. m_root_center_leaf_cx.at(i) = total_cx;
  690. }
  691. pcd_cnt.push_back(total_cnt);
  692. bool has_seedling = total_cnt > th_pcd_size;
  693. if (has_seedling) {
  694. m_root_center_with_occlusion.at(i) = 2;
  695. }
  696. aabb_mins_maxs.push_back(aabb_min);
  697. aabb_mins_maxs.push_back(aabb_max);
  698. }
  699. if (m_pLogger) {
  700. stringstream buff;
  701. buff << m_pcdId << ": root positions points size [inbox] " << m_root_centers.size() << " centers, size_threshold: "<< th_pcd_size<<"\n";
  702. for (int i = 0; i < m_root_centers.size();++i) {
  703. CStemResult& sr = m_root_centers.at(i);
  704. buff << "\tx=" << sr.root_x << ", z=" << sr.root_z
  705. << ", stem_pcd_size=" << sr.stem_size
  706. << ", raw_pcd_size=" << pcd_cnt.at(i) << "\n";
  707. }
  708. m_pLogger->INFO(buff.str());
  709. }
  710. // 显示
  711. if (m_cparam.image_show) {
  712. std::vector<std::vector<int> > clt_line_idx;
  713. std::vector<pcl::PointXYZ>target_root;
  714. double ymin = m_cparam.rs_grab_ymin;
  715. if (m_dtype == 0) { ymin = m_cparam.sc_grab_ymin; }
  716. for (auto&rc : m_root_centers) {
  717. pcl::PointXYZ p(rc.root_x, ymin, rc.root_z);
  718. target_root.push_back(p);
  719. }
  720. viewer_cloud_cluster_box(m_raw_cloud, target_root, aabb_mins_maxs, clt_line_idx, std::string("seedling root centers"));
  721. }
  722. }
  723. int CRootStockGrabPoint::get_point_count_inbox(const CStemResult& sr,
  724. pcl::PointXYZ& aabb_min,
  725. pcl::PointXYZ& aabb_max,
  726. Eigen::Vector4f& centroid)
  727. {
  728. double seedling_distance = m_cparam.rs_grab_seedling_dist;
  729. double min_y = m_cparam.rs_grab_ymin;
  730. if (m_dtype == 0) {
  731. seedling_distance = m_cparam.sc_grab_seedling_dist;
  732. min_y = m_cparam.sc_grab_ymin;
  733. }
  734. double min_x = sr.root_x - 0.5 * seedling_distance;
  735. double max_x = sr.root_x + 0.5 * seedling_distance;
  736. double min_z = sr.root_z - 1.5 * seedling_distance;
  737. double max_z = sr.root_z + 0.5 * seedling_distance;
  738. double max_y = min_y + 150.0; //假定苗高150mm
  739. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  740. pcl::CropBox<pcl::PointXYZ> box_filter;
  741. box_filter.setMin(Eigen::Vector4f(min_x, min_y, min_z, 1));
  742. box_filter.setMax(Eigen::Vector4f(max_x, max_y, max_z, 1));
  743. box_filter.setNegative(false);
  744. box_filter.setInputCloud(m_raw_cloud);
  745. box_filter.filter(*cloud_inbox);
  746. int count = cloud_inbox->points.size();
  747. if (count > 0) {
  748. pcl::compute3DCentroid(*cloud_inbox, centroid);
  749. }
  750. else {
  751. centroid(0) = 0.5 * (min_x + max_x);
  752. centroid(1) = min_y;
  753. centroid(2) = 0.5 * (min_z + max_z);
  754. centroid(3) = 1.0;
  755. }
  756. aabb_min.x = min_x;
  757. aabb_min.y = min_y;
  758. aabb_min.z = min_z;
  759. aabb_max.x = max_x;
  760. aabb_max.y = max_y;
  761. aabb_max.z = max_z;
  762. return count;
  763. }
  764. // 统计inbox点云数量和重心
  765. void CRootStockGrabPoint::get_point_centriod(
  766. std::vector<CStemResult>& root_centers, //input
  767. std::vector<int>&counts, //output
  768. std::vector<Eigen::Vector4f>& centroids //output
  769. )
  770. {
  771. counts.clear();
  772. centroids.clear();
  773. for (auto& sr : root_centers) {
  774. pcl::PointXYZ aabb_min, aabb_max;
  775. Eigen::Vector4f centroid;
  776. int cnt = get_point_count_inbox(sr, aabb_min, aabb_max, centroid);
  777. counts.push_back(cnt);
  778. centroids.push_back(centroid);
  779. }
  780. }
  781. //统计inbox点云在x方向的分布情况
  782. void CRootStockGrabPoint::get_point_x_hist(
  783. std::vector<int>& x_hist //output
  784. )
  785. {
  786. double seedling_distance = m_cparam.rs_grab_seedling_dist;
  787. double x_min = m_cparam.rs_grab_xmin;
  788. double x_max = m_cparam.rs_grab_xmax;
  789. double y_min = m_cparam.rs_grab_ymin;
  790. double y_max = y_min + 150.0;
  791. double z_min = m_cparam.rs_grab_zmin - seedling_distance;
  792. double z_max = m_cparam.rs_grab_zmax + seedling_distance/4.0;
  793. if (m_dtype == 0) {
  794. //穗苗
  795. seedling_distance = m_cparam.sc_grab_seedling_dist;
  796. x_min = m_cparam.sc_grab_xmin;
  797. x_max = m_cparam.sc_grab_xmax;
  798. y_min = m_cparam.sc_grab_ymin;
  799. y_max = y_min + 150.0;
  800. z_min = m_cparam.sc_grab_zmin - seedling_distance;
  801. z_max = m_cparam.sc_grab_zmax;
  802. }
  803. double binw = 5;
  804. int x0 = int(x_min);
  805. int x1 = int(x_max);
  806. int h_size = int((x1 - x0)/binw);
  807. if (h_size <= 0) {
  808. h_size = 1;
  809. }
  810. int idx = 0;
  811. x_hist.assign(h_size, 0);
  812. for (auto&pt : m_raw_cloud->points) {
  813. if(pt.y >= y_min && pt.y < y_max &&
  814. pt.x >=x_min && pt.x < x_max &&
  815. pt.z >= z_min && pt.z < z_max)
  816. {
  817. idx = int((pt.x - x0) / binw);
  818. if (idx >= 0 && idx < h_size) {
  819. x_hist.at(idx)++;
  820. }
  821. }
  822. }
  823. //显示结果
  824. if (m_cparam.image_show) {
  825. pcl::visualization::PCLVisualizer viewer(m_pcdId + std::string(": x histogram"));
  826. viewer.setBackgroundColor(0.35, 0.35, 0.35);
  827. viewer.addCoordinateSystem();
  828. viewer.addPointCloud<pcl::PointXYZ>(m_raw_cloud, "raw_cloud");
  829. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "raw_cloud");
  830. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "raw_cloud");
  831. viewer.addCube(x_min, x_max, y_min, y_max, z_min, z_max, 0.75, 0.0, 0.0, "AABB_");
  832. viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION,
  833. pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "AABB_");
  834. pcl::PointXYZ px0, px1, py1, pz1;
  835. px0.x = 0;
  836. px0.y = 0;
  837. px0.z = 0;
  838. px1.x = 10.0;
  839. px1.y = 0;
  840. px1.z = 0;
  841. py1.x = 0;
  842. py1.y = 10.0;
  843. py1.z = 0;
  844. pz1.x = 0;
  845. pz1.y = 0;
  846. pz1.z = 10.0;
  847. viewer.addLine(px0, px1, 255, 0, 0, "x");
  848. viewer.addLine(px0, py1, 0, 255, 0, "y");
  849. viewer.addLine(px0, pz1, 0, 0, 255, "z");
  850. while (!viewer.wasStopped()) {
  851. viewer.spinOnce(100);
  852. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  853. }
  854. }
  855. }
  856. void CRootStockGrabPoint::get_leaf_point_count_inbox(
  857. const CStemResult& sr,//input
  858. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //input 输入点云数据
  859. std::vector<int>& leaf_idx, //input
  860. pcl::PointXYZ& aabb_min,//output
  861. pcl::PointXYZ& aabb_max,//output
  862. int& total_cnt, //output
  863. int& leaf_cnt, //output
  864. double& total_cx, //output
  865. double& leaf_cx //output
  866. )
  867. {
  868. //计算每一个穴位叶子遮挡的点云数量(以及整体点云数量),并计算x方向的中心
  869. double seedling_distance = m_cparam.rs_grab_seedling_dist;
  870. double min_y = m_cparam.rs_grab_ymin;
  871. double max_y = m_cparam.rs_grab_ymax;
  872. if (m_dtype == 0) {
  873. seedling_distance = m_cparam.sc_grab_seedling_dist;
  874. min_y = m_cparam.sc_grab_ymin;
  875. max_y = m_cparam.sc_grab_ymax;
  876. }
  877. double min_x = sr.root_x - 0.5 * seedling_distance;
  878. double max_x = sr.root_x + 0.5 * seedling_distance;
  879. double min_z = sr.root_z - 0.75 * seedling_distance;
  880. double max_z = sr.root_z + 0.25 * seedling_distance;
  881. aabb_min.x = min_x;
  882. aabb_min.y = min_y;
  883. aabb_min.z = min_z;
  884. aabb_max.x = max_x;
  885. aabb_max.y = max_y;
  886. aabb_max.z = max_z;
  887. total_cnt = 0;
  888. leaf_cnt = 0;
  889. total_cx = 1.0e6;
  890. leaf_cx = 1.0e6;
  891. std::vector<double>xs;
  892. for (auto&pt : in_cloud->points) {
  893. if (pt.y >= min_y && pt.y <= max_y &&
  894. pt.x >= min_x && pt.x <= max_x &&
  895. pt.z >= min_z && pt.z <= max_z)
  896. {
  897. total_cnt++;
  898. xs.push_back(pt.x);
  899. }
  900. }
  901. if (total_cnt == 0) { return; }
  902. int med_idx = int(0.5 * xs.size());
  903. std::sort(xs.begin(), xs.end());
  904. total_cx = xs.at(med_idx);
  905. //leaf center
  906. xs.clear();
  907. for (auto&i : leaf_idx) {
  908. pcl::PointXYZ& pt = in_cloud->points.at(i);
  909. if (pt.y >= min_y && pt.y <= max_y &&
  910. pt.x >= min_x && pt.x <= max_x &&
  911. pt.z >= min_z && pt.z <= max_z)
  912. {
  913. leaf_cnt++;
  914. xs.push_back(pt.x);
  915. }
  916. }
  917. if (leaf_cnt == 0) { return; }
  918. med_idx = int(0.5 * xs.size());
  919. std::sort(xs.begin(), xs.end());
  920. leaf_cx = xs.at(med_idx);
  921. return;
  922. }
  923. //生成结果图片
  924. void CRootStockGrabPoint::gen_result_img(
  925. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud_raw,//输入,未经过滤的整体点云in_cloud_raw,
  926. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //输入,整体点云cloud_dowm_sampled,
  927. pcl::PointXYZ& selected_pt, //输入,selected_pt,
  928. pcl::PointXYZ& selected_pt_ref, //输入,selected_pt_ref,
  929. pcl::PointXYZ& rs_grab_pt, //输入,砧木固定抓取点,
  930. std::vector<float>&fork_ys, //输入,forkys
  931. const PositionInfo& posinfo, //输入,
  932. cv::Mat& rst_img //输出,图片, 640*1280
  933. )
  934. {
  935. if (rst_img.empty()) { return; }
  936. if (rst_img.rows != 640 && rst_img.cols != 1280) { return; }
  937. int cx = 640; //图像中心点0
  938. int cy = 320; //图像中心点0
  939. float res = 0.33333; //分辨率,1个像素0.333mm
  940. //绘制坐标轴
  941. int arrow_len = 20;
  942. cv::line(rst_img, cv::Point(0, cy), cv::Point(cx, cy), cv::Scalar(128,128,128));
  943. cv::line(rst_img, cv::Point(0, cy), cv::Point(arrow_len, cy - int(arrow_len/2)), cv::Scalar(128, 128, 128));
  944. cv::line(rst_img, cv::Point(0, cy), cv::Point(arrow_len, cy + int(arrow_len/2)), cv::Scalar(128, 128, 128));
  945. cv::line(rst_img, cv::Point(cx, 0), cv::Point(cx, cy), cv::Scalar(128, 128, 128));
  946. cv::line(rst_img, cv::Point(cx, 0), cv::Point(cx - int(arrow_len/2), arrow_len), cv::Scalar(128, 128, 128));
  947. cv::line(rst_img, cv::Point(cx, 0), cv::Point(cx + int(arrow_len/2), arrow_len), cv::Scalar(128, 128, 128));
  948. cv::putText(rst_img, std::string("x"), cv::Point(20, cy-10), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(128, 128, 128));
  949. cv::putText(rst_img, std::string("y"), cv::Point(cx+10, 20), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(128, 128, 128));
  950. //绘制所有点
  951. int x, y;
  952. for (auto&pt : in_cloud_raw->points) {
  953. x = cx - int(pt.x / res + 0.5);
  954. y = cy - int(pt.y / res + 0.5);
  955. if (x < 0 || x >= rst_img.cols) { continue; }
  956. if (y < 0 || y >= rst_img.rows) { continue; }
  957. rst_img.at<cv::Vec3b>(y, x)[0] = 60;
  958. rst_img.at<cv::Vec3b>(y, x)[1] = 20;
  959. rst_img.at<cv::Vec3b>(y, x)[2] = 220;
  960. }
  961. for (auto&pt : in_cloud->points) {
  962. x = cx - int(pt.x / res + 0.5);
  963. y = cy - int(pt.y / res + 0.5);
  964. if (x < 0 || x >= rst_img.cols) { continue; }
  965. if (y < 0 || y >= rst_img.rows) { continue; }
  966. rst_img.at<cv::Vec3b>(y, x)[0] = 0;
  967. rst_img.at<cv::Vec3b>(y, x)[1] = 225;
  968. rst_img.at<cv::Vec3b>(y, x)[2] = 0;
  969. }
  970. //绘制抓取点坐标
  971. int grab_x = cx - int(selected_pt.x / res + 0.5);
  972. int grab_y = cy - int(selected_pt.y / res + 0.5);
  973. int radius = 30;
  974. if (m_dtype == 1) {
  975. //如果是砧木,固定y值的抓取点
  976. grab_x = cx - int(rs_grab_pt.x / res + 0.5);
  977. grab_y = cy - int(rs_grab_pt.y / res + 0.5);
  978. }
  979. cv::line(rst_img, cv::Point(grab_x - radius, grab_y - radius), cv::Point(grab_x + radius, grab_y + radius), cv::Scalar(0, 215, 255));
  980. cv::line(rst_img, cv::Point(grab_x - radius, grab_y + radius), cv::Point(grab_x + radius, grab_y - radius), cv::Scalar(0, 215, 255));
  981. //如果是遮挡,画一个圆
  982. if ((m_dtype == 0 && posinfo.sc_width == 0) || (m_dtype == 1 && posinfo.rs_width == 0)) {
  983. cv::circle(rst_img, cv::Point(grab_x, grab_y), radius, cv::Scalar(0, 215, 255));
  984. }
  985. //绘制茎节点坐标
  986. radius = 15;
  987. if (m_dtype == 0) {
  988. int fork_x = cx - int(selected_pt_ref.x / res + 0.5);
  989. int fork_y = cy - int(selected_pt_ref.y / res + 0.5);
  990. cv::line(rst_img, cv::Point(fork_x - radius, fork_y), cv::Point(fork_x + radius, fork_y), cv::Scalar(153, 51, 255));
  991. }
  992. else {
  993. for (auto&fy : fork_ys) {
  994. int fork_x = grab_x;
  995. int fork_y = cy - int(fy / res + 0.5);
  996. cv::line(rst_img, cv::Point(fork_x - radius, fork_y), cv::Point(fork_x + radius, fork_y), cv::Scalar(153, 51, 255));
  997. }
  998. }
  999. //在图片中写入文件名字
  1000. cv::putText(rst_img, m_pcdId, cv::Point(20, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(128, 128, 128));
  1001. }
  1002. int CRootStockGrabPoint::read_ply_file(const char* fn)
  1003. {
  1004. m_raw_cloud.reset( new pcl::PointCloud<pcl::PointXYZ>);
  1005. if (pcl::io::loadPLYFile<pcl::PointXYZ>(fn, *m_raw_cloud) == -1) {
  1006. if (m_pLogger) {
  1007. m_pLogger->ERRORINFO(m_pcdId + ": could not load file: "+std::string(fn));
  1008. }
  1009. return (-1);
  1010. }
  1011. if (m_pLogger) {
  1012. stringstream buff;
  1013. buff << m_pcdId <<": load raw point cloud " << m_raw_cloud->width * m_raw_cloud->height << " data points";
  1014. m_pLogger->INFO(buff.str());
  1015. }
  1016. return m_raw_cloud->width * m_raw_cloud->height;
  1017. }
  1018. double CRootStockGrabPoint::compute_nearest_neighbor_distance(pcl::PointCloud<pcl::PointXYZ>::Ptr pcd)
  1019. {
  1020. pcl::KdTreeFLANN<pcl::PointXYZ> tree;
  1021. tree.setInputCloud(pcd);
  1022. int k = 2;
  1023. double res = 0.0;
  1024. int n_points = 0;
  1025. for (size_t i = 0; i < pcd->size(); ++i) {
  1026. std::vector<int> idx(k);
  1027. std::vector<float> sqr_distances(k);
  1028. if (tree.nearestKSearch(i, k, idx, sqr_distances) == k) {
  1029. for (int id = 1; id < k; ++id) {
  1030. res += sqrt(sqr_distances.at(id));
  1031. ++n_points;
  1032. }
  1033. }
  1034. }
  1035. if (n_points > 0) {
  1036. res /= (double)n_points;
  1037. }
  1038. return res;
  1039. }
  1040. ////////////////////////////////////////////////////////////
  1041. //叶子剔除, 假设叶子和茎是分离的,用欧式聚类分割
  1042. void CRootStockGrabPoint::leaf_filter(
  1043. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //输入,降采样的点云
  1044. std::vector<int> &stem_cloud_idx //输出,除了叶子的点云序号
  1045. )
  1046. {
  1047. //采用欧式距离聚类,对每一类的点云进行分析,剔除叶子
  1048. stem_cloud_idx.clear();
  1049. std::vector<pcl::PointIndices> cluster_indices;
  1050. pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);
  1051. tree->setInputCloud(in_cloud);
  1052. pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec;
  1053. ec.setClusterTolerance(2.5);
  1054. ec.setMinClusterSize(30);
  1055. ec.setMaxClusterSize(20000);
  1056. ec.setSearchMethod(tree);
  1057. ec.setInputCloud(in_cloud);
  1058. ec.extract(cluster_indices);
  1059. for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin();
  1060. it != cluster_indices.end(); ++it) {
  1061. pcl::PointCloud<pcl::PointXYZ>::Ptr cluster_cloud(new pcl::PointCloud<pcl::PointXYZ>);
  1062. pcl::copyPointCloud(*in_cloud, *it, *cluster_cloud);
  1063. //计算点云的pca
  1064. Eigen::Vector4f pcaCenteroid;
  1065. pcl::compute3DCentroid(*cluster_cloud, pcaCenteroid);
  1066. Eigen::Matrix3f covariance;
  1067. pcl::computeCovarianceMatrix(*cluster_cloud, pcaCenteroid, covariance);
  1068. Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigen_solver(covariance, Eigen::ComputeEigenvectors);
  1069. Eigen::Vector3f eigenValuesPCA = eigen_solver.eigenvalues();
  1070. float e1, e2, e3;
  1071. e1 = std::sqrt(eigenValuesPCA(2));
  1072. e2 = std::sqrt(eigenValuesPCA(1));
  1073. e3 = std::sqrt(eigenValuesPCA(0));
  1074. float a1d = (e1 - e2) / e1;
  1075. float a2d = (e2 - e3) / e1;
  1076. float a3d = e3 / e1;
  1077. if (m_pLogger) {
  1078. stringstream buff;
  1079. buff << m_pcdId << ": ads=(" << a1d << "," << a2d << "," << a3d << "), pca_eigem_values=(" << e1
  1080. << "," << e2 << "," << e3 << "), cluster_size=" << it->indices.size();
  1081. m_pLogger->INFO(buff.str());
  1082. }
  1083. if (m_cparam.image_show) {
  1084. if (a1d < 0.75) {
  1085. viewer_cloud(cluster_cloud, string("cluster_leaf"));
  1086. }
  1087. else {
  1088. viewer_cloud(cluster_cloud, string("cluster_stem"));
  1089. }
  1090. }
  1091. /*
  1092. 特征值归一化处理: a1d = (e1 - e2) / e1
  1093. a2d = (e2 - e3) / e1
  1094. a3d = e3 / e1
  1095. ei = sqrt(lamda_i)
  1096. 当点云线状分布时,a1d = 1, a2d = 0, a3d = 0
  1097. 当点云面状分布时,a1d = 0, a2d = 1, a3d = 0
  1098. 当点云球状分布时,a1d = 0, a2d = 0, a3d = 1
  1099. */
  1100. if (a1d < 0.75) { continue; }
  1101. for (int idx : it->indices) {
  1102. stem_cloud_idx.push_back(idx);
  1103. }
  1104. }
  1105. }
  1106. // 基于孤立点滤除的方法检测叶子区域
  1107. void CRootStockGrabPoint::leaf_filter_ror(
  1108. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //input 输入点云数据
  1109. std::vector<int> &stem_cloud_idx, //output, 过滤后的点云序号
  1110. std::vector<int>& leaf_idx //output, 叶子的点云序号
  1111. )
  1112. {
  1113. //计算点云平均间距
  1114. //double mean_dist = 0.0;
  1115. //cloud_mean_dist(in_cloud, mean_dist);
  1116. //计算点云过滤半径和点数阈值
  1117. double stem_diameter = m_cparam.rs_grab_stem_diameter;
  1118. if (m_dtype == 0) { stem_diameter = m_cparam.sc_grab_stem_diameter; }
  1119. double remove_radius = stem_diameter;
  1120. double ror_ratio = m_cparam.rs_grab_ror_ratio;
  1121. if (m_dtype == 0){ror_ratio = m_cparam.sc_grab_ror_ratio;}
  1122. int nb_points = ror_ratio* stem_diameter * stem_diameter * 2.0 / m_cloud_mean_dist / m_cloud_mean_dist; // (2d*d + pi *d*d) /2
  1123. if (m_pLogger) {
  1124. stringstream buff;
  1125. buff << m_pcdId << ": ror_ratio=" << ror_ratio << ", ror filter nb_points=" << nb_points;
  1126. m_pLogger->INFO(buff.str());
  1127. }
  1128. //获取叶片的点云
  1129. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_leaf(new pcl::PointCloud<pcl::PointXYZ>);
  1130. pcl::RadiusOutlierRemoval<pcl::PointXYZ> ror(true);
  1131. ror.setInputCloud(in_cloud);
  1132. ror.setRadiusSearch(remove_radius);
  1133. ror.setMinNeighborsInRadius(nb_points);
  1134. ror.filter(*cloud_leaf);
  1135. //通过叶片点云寻找附近remove_radius内的近邻点,当做叶子点云序号
  1136. std::set<int> leaf_idx_set;
  1137. int nres;
  1138. std::vector<int> indices;
  1139. std::vector<float> sqr_distances;
  1140. pcl::search::KdTree<pcl::PointXYZ> tree;
  1141. tree.setInputCloud(in_cloud);
  1142. for (size_t i = 0; i < cloud_leaf->size(); ++i)
  1143. {
  1144. nres = tree.radiusSearch(cloud_leaf->points.at(i), remove_radius, indices, sqr_distances);
  1145. for (int& idx : indices) {
  1146. leaf_idx_set.insert(idx);
  1147. }
  1148. }
  1149. leaf_idx.clear();
  1150. leaf_idx.assign(leaf_idx_set.begin(), leaf_idx_set.end());
  1151. //in_img是经过开运算的图像,其中像素位置的点云为叶子区域
  1152. std::vector<int>::iterator lit;
  1153. for (int i = 0; i < in_cloud->points.size(); ++i) {
  1154. lit = std::find(leaf_idx.begin(), leaf_idx.end(), i);
  1155. if (lit == leaf_idx.end()) {
  1156. stem_cloud_idx.push_back(i);
  1157. }
  1158. }
  1159. //显示开运算的结果
  1160. if (m_cparam.image_show) {
  1161. pcl::PointCloud<pcl::PointXYZ>::Ptr stem_cloud(new pcl::PointCloud<pcl::PointXYZ>);
  1162. pcl::PointCloud<pcl::PointXYZ>::Ptr leaf_cloud(new pcl::PointCloud < pcl::PointXYZ>);
  1163. pcl::copyPointCloud(*in_cloud, stem_cloud_idx, *stem_cloud);
  1164. pcl::copyPointCloud(*in_cloud, leaf_idx, *leaf_cloud);
  1165. pcl::visualization::PCLVisualizer viewer("open cloud");
  1166. viewer.addCoordinateSystem();
  1167. viewer.addPointCloud<pcl::PointXYZ>(stem_cloud, "stem_cloud");//????????????????
  1168. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "stem_cloud");
  1169. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "stem_cloud");
  1170. viewer.addPointCloud<pcl::PointXYZ>(leaf_cloud, "leaf_cloud");
  1171. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 0, 0, "leaf_cloud");
  1172. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "leaf_cloud");
  1173. while (!viewer.wasStopped()) {
  1174. viewer.spinOnce(100);
  1175. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  1176. }
  1177. }
  1178. }
  1179. void CRootStockGrabPoint::cloud_mean_dist(
  1180. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //input 输入点云数据
  1181. double& mean_dist
  1182. )
  1183. {
  1184. mean_dist = 0.0;
  1185. int n_points = 0;
  1186. int nres;
  1187. std::vector<int> indices(2);
  1188. std::vector<float> sqr_distances(2);
  1189. pcl::search::KdTree<pcl::PointXYZ> tree;
  1190. tree.setInputCloud(in_cloud);
  1191. std::vector<double> distances;
  1192. double dist;
  1193. for (size_t i = 0; i < in_cloud->size(); ++i)
  1194. {
  1195. //Considering the second neighbor since the first is the point itself.
  1196. nres = tree.nearestKSearch(i, 2, indices, sqr_distances);
  1197. if (nres == 2)
  1198. {
  1199. dist = std::sqrt(sqr_distances[1]);
  1200. mean_dist += dist;
  1201. ++n_points;
  1202. distances.push_back(dist);
  1203. }
  1204. }
  1205. std::sort(distances.begin(), distances.end());
  1206. int per10 = int(distances.size() * 0.1);
  1207. mean_dist = distances.at(per10);
  1208. }
  1209. //////////////////////////////////////////////////////////////////////////////////////////
  1210. void CRootStockGrabPoint::gen_all_seedling_positions(
  1211. pcl::PointXYZ&key_center, //输入,已知的苗的坐标
  1212. std::vector<pcl::PointXYZ>&candidate_center //输出,有倾斜苗的坐标
  1213. )
  1214. {
  1215. //生成所有的植株位置,并排序
  1216. candidate_center.clear();
  1217. //找到z最小的那一株,并找出和它一排的那些
  1218. float step_harf = m_cparam.rs_grab_seedling_dist / 2.0;
  1219. float xmin = m_cparam.rs_grab_xmin;
  1220. float xmax = m_cparam.rs_grab_xmax;
  1221. float zmin = m_cparam.rs_grab_zmin;
  1222. float zmax = m_cparam.rs_grab_zmax;
  1223. int col_from = -8;
  1224. int col_to = 8;
  1225. int col_step = 1;
  1226. if (m_dtype == 0) {
  1227. step_harf = m_cparam.sc_grab_seedling_dist / 2.0;
  1228. xmin = m_cparam.sc_grab_xmin;
  1229. xmax = m_cparam.sc_grab_xmax;
  1230. zmin = m_cparam.sc_grab_zmin;
  1231. zmax = m_cparam.sc_grab_zmax;
  1232. }
  1233. // 生成所有可能的植株位置中心点
  1234. for (int row = -8; row <= 4; row += 1) {
  1235. float cz = key_center.z + row * step_harf/2.0;
  1236. if (cz < zmin || cz > zmax) { continue; }
  1237. for (int col = 4*col_from; col <= 4*col_to; col += col_step) {
  1238. float cx = key_center.x + col * step_harf/2;
  1239. if (cx < xmin || cx > xmax) { continue; }
  1240. //保存
  1241. pcl::PointXYZ pc(cx, 0.0, cz);
  1242. candidate_center.push_back(pc);
  1243. }
  1244. }
  1245. }
  1246. void CRootStockGrabPoint::nms_box(
  1247. std::vector<pcl::PointXYZ>&clt_root_v,
  1248. std::vector<float>&valid_box_cc_dist,
  1249. float hole_step_radius,
  1250. std::vector<pcl::PointXYZ>& target_toot)
  1251. {
  1252. target_toot.clear();
  1253. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
  1254. for (auto&p : clt_root_v) { cloud->points.push_back(p); }
  1255. pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
  1256. kdtree.setInputCloud(cloud);
  1257. std::vector<int>idx;
  1258. std::vector<float>dist_sqr;
  1259. std::vector<int> tar_idx;
  1260. for (size_t i = 0; i < cloud->points.size(); ++i) {
  1261. int k = kdtree.radiusSearch(cloud->points.at(i), hole_step_radius, idx, dist_sqr);
  1262. std::vector<float> cc_tmp;
  1263. for (auto& j : idx) { cc_tmp.push_back(valid_box_cc_dist.at(j)); }
  1264. int min_id = std::min_element(cc_tmp.begin(), cc_tmp.end()) - cc_tmp.begin();
  1265. if (min_id == 0) {
  1266. tar_idx.push_back(i);
  1267. }
  1268. }
  1269. for (auto& i : tar_idx) {
  1270. target_toot.push_back(clt_root_v.at(i));
  1271. }
  1272. }
  1273. //通过指定位置内,取部分点云分析是否存在真正的茎,真茎位置保存到target_filtered
  1274. void CRootStockGrabPoint::line_filter(
  1275. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //输入点云
  1276. float radius, //输入,取点半径
  1277. float ymin,
  1278. float ymax,
  1279. std::vector<pcl::PointXYZ>&target_root, //输入,位置
  1280. std::vector<pcl::PointXYZ>&target_filtered, //输出,位置
  1281. std::vector<pcl::PointXYZ>&target_filtered_root, //输出,茎上根部点坐标
  1282. std::vector<std::vector<int>>&target_filtered_element, //输出,茎上点index
  1283. std::vector<pcl::ModelCoefficients::Ptr>& target_filtered_models//输出,茎直线模型
  1284. )
  1285. {
  1286. target_filtered.clear();
  1287. target_filtered_element.clear();
  1288. target_filtered_root.clear();
  1289. if (target_root.size() == 0) { return; }
  1290. for (auto&p : target_root) {
  1291. // 构建box,获取植株点云
  1292. pcl::PointCloud<pcl::PointXYZ>::Ptr seedling_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  1293. pcl::CropBox<pcl::PointXYZ> box_filter;
  1294. std::vector<int>inbox_idx;
  1295. pcl::PointXYZ min_point_aabb_ex;
  1296. pcl::PointXYZ max_point_aabb_ex;
  1297. min_point_aabb_ex.x = p.x - radius;
  1298. min_point_aabb_ex.y = ymin;
  1299. min_point_aabb_ex.z = p.z - radius;
  1300. max_point_aabb_ex.x = p.x + radius;
  1301. max_point_aabb_ex.y = ymax;
  1302. max_point_aabb_ex.z = p.z + radius;
  1303. box_filter.setMin(Eigen::Vector4f(min_point_aabb_ex.x, min_point_aabb_ex.y, min_point_aabb_ex.z, 1));
  1304. box_filter.setMax(Eigen::Vector4f(max_point_aabb_ex.x, max_point_aabb_ex.y, max_point_aabb_ex.z, 1));
  1305. box_filter.setNegative(false);
  1306. box_filter.setInputCloud(in_cloud);
  1307. box_filter.filter(inbox_idx);
  1308. pcl::copyPointCloud(*in_cloud, inbox_idx, *seedling_inbox);
  1309. //植株点云直线查找
  1310. //找到inbox点云中的直线
  1311. float stem_radius = m_cparam.rs_grab_stem_diameter / 2.0;
  1312. if (m_dtype == 0) {
  1313. stem_radius = m_cparam.sc_grab_stem_diameter / 2.0;
  1314. }
  1315. pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
  1316. pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
  1317. pcl::SACSegmentation<pcl::PointXYZ> seg;
  1318. seg.setOptimizeCoefficients(true);
  1319. seg.setModelType(pcl::SACMODEL_LINE);
  1320. seg.setDistanceThreshold(stem_radius);
  1321. seg.setInputCloud(seedling_inbox);
  1322. seg.segment(*inliers, *coefficients);
  1323. pcl::PointCloud<pcl::PointXYZ>::Ptr stem_cloud(new pcl::PointCloud<pcl::PointXYZ>);
  1324. pcl::copyPointCloud(*seedling_inbox, *inliers, *stem_cloud);
  1325. //稳定性检测:通过扩大直径检测范围,得到直线上的点应基本保持一致,如果不一致,就是茎不显著,可能是叶子内找到的
  1326. pcl::ModelCoefficients::Ptr coefficients_ex(new pcl::ModelCoefficients);
  1327. pcl::PointIndices::Ptr inliers_ex(new pcl::PointIndices);
  1328. seg.setDistanceThreshold(1.5*stem_radius);
  1329. seg.segment(*inliers_ex, *coefficients_ex);
  1330. float ratio_ex = inliers_ex->indices.size() / (float)(inliers->indices.size());
  1331. float rex_th = 1.5;
  1332. if (m_pLogger) {
  1333. stringstream buff;
  1334. buff << m_pcdId << ": stem externed line points ext_ratio= " << ratio_ex << ", threshold is "<< rex_th;
  1335. m_pLogger->INFO(buff.str());
  1336. }
  1337. if (ratio_ex > rex_th) {
  1338. continue;
  1339. }
  1340. //点数过滤
  1341. int min_stem_pts = m_cparam.rs_grab_stem_min_pts;
  1342. if (m_dtype == 0) { min_stem_pts = m_cparam.sc_grab_stem_min_pts; }
  1343. if (inliers->indices.size() < int(min_stem_pts / 2)) { continue; }
  1344. //y方向分布范围滤波
  1345. float y_length_th = 10.0;
  1346. pcl::PointXYZ min_v;
  1347. pcl::PointXYZ max_v;
  1348. pcl::getMinMax3D(*stem_cloud, min_v, max_v);
  1349. float dy = max_v.y - min_v.y;
  1350. if (dy<y_length_th && dy / (ymax - ymin) < 0.25) { continue; }
  1351. //y方向分布中心滤波
  1352. float dy_c = 0.5*(max_v.y + min_v.y);
  1353. if ((dy_c - ymin) / (ymax - ymin) > 0.75) { continue; }
  1354. //倾斜角度过滤
  1355. float xz = std::sqrt(coefficients->values.at(3) * coefficients->values.at(3) +
  1356. coefficients->values.at(5) * coefficients->values.at(5));
  1357. float a = std::atan2f(coefficients->values.at(4), xz);
  1358. a = std::fabs(a) * 180.0 / 3.14159;
  1359. if (a < 60.0) { continue; }
  1360. target_filtered.push_back(p);
  1361. //有效茎长计算
  1362. std::vector<int> stem_y_count_hist;
  1363. get_line_project_hist(stem_cloud, coefficients, stem_y_count_hist);
  1364. std::vector<int> stem_y_count_hist_valid;
  1365. for (auto&v : stem_y_count_hist) {
  1366. if (v > 2) {
  1367. stem_y_count_hist_valid.push_back(v);
  1368. }
  1369. }
  1370. double valid_mu = get_hist_mean(stem_y_count_hist_valid);
  1371. int cnt_th = static_cast<int>(valid_mu/2.0);
  1372. if (cnt_th < 3) { cnt_th = 2; }
  1373. float valid_length = 0.0;
  1374. std::vector<int> stem_y_mask;
  1375. for (auto& c : stem_y_count_hist) {
  1376. if (c > cnt_th) {
  1377. valid_length += 1.0;
  1378. stem_y_mask.push_back(1);
  1379. }
  1380. else {
  1381. stem_y_mask.push_back(0);
  1382. }
  1383. }
  1384. //填补空
  1385. for (int i = 1; i < stem_y_mask.size() - 1; ++i) {
  1386. if (stem_y_mask.at(i) == 0 && stem_y_mask.at(i - 1) == 1 && stem_y_mask.at(i + 1) == 1) {
  1387. stem_y_mask.at(i) = 1;
  1388. }
  1389. }
  1390. //找出最长的连续段的长度
  1391. int longest_segment = 0;
  1392. int start = 0;
  1393. for (int i = 0; i < stem_y_mask.size(); ++i) {
  1394. if (i == 0 ) {
  1395. if (stem_y_mask.at(i) == 1) {
  1396. start = i;
  1397. }
  1398. continue;
  1399. }
  1400. if (i == stem_y_mask.size() - 1 ) {
  1401. if (stem_y_mask.at(i) == 1) {
  1402. int length = i - start + 1;
  1403. if (length > longest_segment) { longest_segment = length; }
  1404. }
  1405. continue;
  1406. }
  1407. if (stem_y_mask.at(i - 1) == 0 && stem_y_mask.at(i) == 1) {
  1408. start = i;
  1409. continue;
  1410. }
  1411. if (stem_y_mask.at(i - 1) == 1 && stem_y_mask.at(i) == 0) {
  1412. int length = i - start;
  1413. if (length > longest_segment) { longest_segment = length; }
  1414. continue;
  1415. }
  1416. }
  1417. if (longest_segment<10.0 && valid_length / (ymax - ymin) < 0.35) { continue; }
  1418. float min_y = 10000.0;
  1419. int min_y_idx = -1;
  1420. for (size_t j = 0; j < stem_cloud->points.size();++j) {
  1421. pcl::PointXYZ &spt = stem_cloud->at(j);
  1422. if (spt.y < min_y) {
  1423. min_y = spt.y;
  1424. min_y_idx = j;
  1425. }
  1426. }
  1427. pcl::PointXYZ tr_pt(stem_cloud->points.at(min_y_idx).x, stem_cloud->points.at(min_y_idx).y, stem_cloud->points.at(min_y_idx).z);
  1428. target_filtered_root.push_back(tr_pt);
  1429. int idx_raw = 0;
  1430. std::vector<int> out_idx;
  1431. for (auto& idx : inliers->indices) {
  1432. idx_raw = inbox_idx.at(idx);
  1433. out_idx.push_back(idx_raw);
  1434. }
  1435. target_filtered_element.push_back(out_idx);
  1436. target_filtered_models.push_back(coefficients);
  1437. // debug show
  1438. /*if (m_cparam.image_show) {
  1439. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_line(new pcl::PointCloud<pcl::PointXYZ>);
  1440. pcl::copyPointCloud(*seedling_inbox, *inliers, *cloud_line);
  1441. pcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer("line in cluster"));
  1442. viewer->addPointCloud<pcl::PointXYZ>(seedling_inbox, "cluster");
  1443. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "cluster");
  1444. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cluster");
  1445. viewer->addPointCloud(cloud_line, "fit_line");
  1446. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0, 1, 0, "fit_line");
  1447. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "fit_line");
  1448. while (!viewer->wasStopped()) {
  1449. viewer->spinOnce(100);
  1450. }
  1451. }*/
  1452. }
  1453. }
  1454. void CRootStockGrabPoint::get_edge_line(
  1455. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud,
  1456. std::vector<int>& edge_idx,
  1457. pcl::ModelCoefficients::Ptr coefficients)
  1458. {
  1459. pcl::PointCloud<pcl::PointXYZ>::Ptr edges(new pcl::PointCloud<pcl::PointXYZ>);
  1460. pcl::copyPointCloud(*in_cloud, edge_idx, *edges);
  1461. //植株点云直线查找
  1462. //找到inbox点云中的直线
  1463. float stem_radius = 2.0 * m_cloud_mean_dist;
  1464. //pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
  1465. pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
  1466. pcl::SACSegmentation<pcl::PointXYZ> seg;
  1467. seg.setOptimizeCoefficients(true);
  1468. seg.setModelType(pcl::SACMODEL_LINE);
  1469. seg.setDistanceThreshold(stem_radius);
  1470. seg.setInputCloud(edges);
  1471. seg.segment(*inliers, *coefficients);
  1472. }
  1473. bool CRootStockGrabPoint::find_seedling_position_key(
  1474. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud,
  1475. std::vector<int> &first_seedling_cloud_idx,
  1476. pcl::PointXYZ&xz_center,
  1477. pcl::ModelCoefficients::Ptr& line_model,
  1478. int& first_row_size
  1479. )
  1480. {
  1481. first_row_size = 0;
  1482. // 确定植株inbox范围
  1483. float hole_step = m_cparam.rs_grab_seedling_dist - 5.0; //穴盘中穴间距
  1484. if (m_dtype == 0) {
  1485. hole_step = m_cparam.sc_grab_seedling_dist - 5.0;
  1486. }
  1487. float hole_step_radius = 2.0 * hole_step / 3.0;
  1488. // 点云降维到xz平面,y=0
  1489. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2d(new pcl::PointCloud < pcl::PointXYZ>);
  1490. pcl::copyPointCloud(*in_cloud, *cloud2d);
  1491. for (auto&pt : *cloud2d) {
  1492. pt.y = 0.0;
  1493. }
  1494. // 在xz平面内统计点的密度
  1495. double radius = m_cparam.rs_grab_stem_diameter;
  1496. if (m_dtype == 0) {
  1497. radius = m_cparam.sc_grab_stem_diameter;
  1498. }
  1499. std::vector<int> counter;
  1500. pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
  1501. kdtree.setInputCloud(cloud2d);
  1502. std::vector<int>idx;
  1503. std::vector<float>dist_sqr;
  1504. for (size_t i = 0; i < cloud2d->points.size(); ++i) {
  1505. int k = kdtree.radiusSearch(cloud2d->points.at(i), radius, idx, dist_sqr);
  1506. counter.push_back(k);
  1507. }
  1508. int max_density_idx = std::max_element(counter.begin(), counter.end()) - counter.begin();
  1509. int max_density = counter.at(max_density_idx);
  1510. if (m_cparam.image_show) {
  1511. //显示密度最大的点的位置
  1512. pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_tmp(new pcl::PointCloud<pcl::PointXYZRGB>);
  1513. pcl::copyPointCloud(*in_cloud, *cloud_tmp);
  1514. for (auto& pt : *cloud_tmp) {
  1515. pt.r = 255;
  1516. pt.g = 255;
  1517. pt.b = 255;
  1518. }
  1519. std::vector<pcl::PointXYZ>cc;
  1520. cc.push_back(in_cloud->points.at(max_density_idx));
  1521. viewer_cloud_cluster(cloud_tmp, cc, string("key"));
  1522. }
  1523. // 生成植株的中心及box
  1524. std::vector<pcl::PointXYZ>clt_root;
  1525. std::vector<pcl::PointXYZ> clt_box;
  1526. float ymin = m_cparam.rs_grab_ymin;
  1527. float ymax = m_cparam.rs_grab_ymax;
  1528. if (m_dtype == 0) {
  1529. ymin = m_cparam.sc_grab_ymin;
  1530. ymax = m_cparam.sc_grab_ymax;
  1531. }
  1532. gen_all_seedling_positions(in_cloud->points.at(max_density_idx), clt_root);
  1533. // 显示生成的每一个候选框
  1534. /*if (m_cparam.image_show) {
  1535. std::vector<std::vector<int> > clt_line_idx;
  1536. std::vector<pcl::PointXYZ> clt_root_v;
  1537. std::vector<pcl::PointXYZ> clt_box_v;
  1538. for (auto&p : clt_root) {
  1539. pcl::PointXYZ p_show(p.x, ymin, p.z);
  1540. clt_root_v.push_back(p_show);
  1541. pcl::PointXYZ min_point_aabb_ex;
  1542. pcl::PointXYZ max_point_aabb_ex;
  1543. min_point_aabb_ex.x = p.x - hole_step_radius;
  1544. min_point_aabb_ex.y = ymin;
  1545. min_point_aabb_ex.z = p.z - hole_step_radius;
  1546. max_point_aabb_ex.x = p.x + hole_step_radius;
  1547. max_point_aabb_ex.y = ymax;
  1548. max_point_aabb_ex.z = p.z + hole_step_radius;
  1549. clt_box_v.push_back(min_point_aabb_ex);
  1550. clt_box_v.push_back(max_point_aabb_ex);
  1551. }
  1552. viewer_cloud_cluster_box(in_cloud, clt_root_v, clt_box_v, clt_line_idx, std::string("candidate_box"));
  1553. }*/
  1554. // 每个位置点云情况,过滤
  1555. std::vector<int> valid_index; //初步有效的矩形index
  1556. std::vector<int> valid_box_pts; //立方体内点云数量
  1557. std::vector<float>valid_box_cc_dist;//重心和矩形中心距离
  1558. for (size_t i = 0; i < clt_root.size();++i) {
  1559. pcl::PointXYZ &p = clt_root.at(i);
  1560. pcl::PointCloud<pcl::PointXYZ>::Ptr seedling_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  1561. pcl::CropBox<pcl::PointXYZ> box_filter;
  1562. std::vector<int>inbox_idx;
  1563. pcl::PointXYZ min_point_aabb_ex;
  1564. pcl::PointXYZ max_point_aabb_ex;
  1565. min_point_aabb_ex.x = p.x - hole_step_radius;
  1566. min_point_aabb_ex.y = ymin;
  1567. min_point_aabb_ex.z = p.z - hole_step_radius;
  1568. max_point_aabb_ex.x = p.x + hole_step_radius;
  1569. max_point_aabb_ex.y = ymax;
  1570. max_point_aabb_ex.z = p.z + hole_step_radius;
  1571. box_filter.setMin(Eigen::Vector4f(min_point_aabb_ex.x, min_point_aabb_ex.y, min_point_aabb_ex.z, 1));
  1572. box_filter.setMax(Eigen::Vector4f(max_point_aabb_ex.x, max_point_aabb_ex.y, max_point_aabb_ex.z, 1));
  1573. box_filter.setNegative(false);
  1574. box_filter.setInputCloud(in_cloud);
  1575. box_filter.filter(inbox_idx);
  1576. pcl::copyPointCloud(*in_cloud, inbox_idx, *seedling_inbox);
  1577. //点数过滤
  1578. if (inbox_idx.size() < int(max_density/3)) { continue; }
  1579. //y方向分布范围滤波
  1580. pcl::PointXYZ min_v;
  1581. pcl::PointXYZ max_v;
  1582. pcl::getMinMax3D(*seedling_inbox, min_v, max_v);
  1583. float dy = max_v.y - min_v.y;
  1584. if (dy / (ymax - ymin) < 0.35) { continue; }
  1585. //y方向分布中心滤波
  1586. float dy_c = 0.5*(max_v.y + min_v.y);
  1587. if ((dy_c-ymin) / (ymax - ymin) > 0.75) { continue; }
  1588. //计算中心
  1589. Eigen::Vector4f mean;
  1590. pcl::compute3DCentroid(*seedling_inbox, mean);
  1591. double cc_dist = std::sqrt((mean[0] - p.x)*(mean[0] - p.x) + (mean[2] - p.z)*(mean[2] - p.z));
  1592. valid_index.push_back(i);
  1593. valid_box_pts.push_back(inbox_idx.size());
  1594. valid_box_cc_dist.push_back((float)cc_dist);
  1595. }
  1596. // 找到局部最大值,找出真正的位置
  1597. std::vector<pcl::PointXYZ> clt_root_v;
  1598. std::vector<pcl::PointXYZ> clt_box_v;
  1599. for (auto&i : valid_index) {
  1600. pcl::PointXYZ&p = clt_root.at(i);
  1601. pcl::PointXYZ p_show(p.x, ymin, p.z);
  1602. clt_root_v.push_back(p_show);
  1603. pcl::PointXYZ min_point_aabb_ex;
  1604. pcl::PointXYZ max_point_aabb_ex;
  1605. min_point_aabb_ex.x = p.x - hole_step_radius;
  1606. min_point_aabb_ex.y = ymin;
  1607. min_point_aabb_ex.z = p.z - hole_step_radius;
  1608. max_point_aabb_ex.x = p.x + hole_step_radius;
  1609. max_point_aabb_ex.y = ymax;
  1610. max_point_aabb_ex.z = p.z + hole_step_radius;
  1611. clt_box_v.push_back(min_point_aabb_ex);
  1612. clt_box_v.push_back(max_point_aabb_ex);
  1613. }
  1614. // 显示
  1615. /*if (m_cparam.image_show) {
  1616. std::vector<std::vector<int> > clt_line_idx;
  1617. viewer_cloud_cluster_box(in_cloud, clt_root_v, clt_box_v, clt_line_idx, std::string("valid_box"));
  1618. }*/
  1619. std::vector<pcl::PointXYZ> target_root;
  1620. nms_box(clt_root_v, valid_box_cc_dist, hole_step_radius, target_root);
  1621. // 显示
  1622. if (m_cparam.image_show) {
  1623. std::vector<std::vector<int> > clt_line_idx;
  1624. std::vector<pcl::PointXYZ>clt_box_tmp;
  1625. for (auto&p : target_root) {
  1626. pcl::PointXYZ p_show(p.x, ymin, p.z);
  1627. clt_root_v.push_back(p_show);
  1628. pcl::PointXYZ min_point_aabb_ex;
  1629. pcl::PointXYZ max_point_aabb_ex;
  1630. min_point_aabb_ex.x = p.x - hole_step_radius;
  1631. min_point_aabb_ex.y = ymin;
  1632. min_point_aabb_ex.z = p.z - hole_step_radius;
  1633. max_point_aabb_ex.x = p.x + hole_step_radius;
  1634. max_point_aabb_ex.y = ymax;
  1635. max_point_aabb_ex.z = p.z + hole_step_radius;
  1636. clt_box_tmp.push_back(min_point_aabb_ex);
  1637. clt_box_tmp.push_back(max_point_aabb_ex);
  1638. }
  1639. viewer_cloud_cluster_box(in_cloud, target_root, clt_box_tmp, clt_line_idx, std::string("nms_box"));
  1640. }
  1641. ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  1642. ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  1643. // 根据得到的位置,直线检测,并过滤
  1644. std::vector<pcl::PointXYZ>target_filtered;
  1645. std::vector<std::vector<int>> target_member;//输出,茎上点index
  1646. std::vector<pcl::PointXYZ>target_filtered_root;
  1647. std::vector<pcl::ModelCoefficients::Ptr> target_filtered_models; //茎直线模型
  1648. line_filter(in_cloud, hole_step_radius,ymin,ymax, target_root, target_filtered,
  1649. target_filtered_root,
  1650. target_member,
  1651. target_filtered_models);
  1652. //根据实际得到的茎的位置,更新当前茎状态
  1653. m_pSeedlingStatus->real_result_update(target_filtered_root);
  1654. m_pSeedlingStatus->occlusion_result_update(m_root_center_with_occlusion);
  1655. m_pSeedlingStatus->get_stem_status(m_root_center_with_seedling);
  1656. if (m_pLogger) {
  1657. stringstream buff;
  1658. buff << m_pcdId << ": stem status: ";
  1659. for (auto&st : m_root_center_with_seedling) {
  1660. buff << st << "\t";
  1661. }
  1662. m_pLogger->INFO(buff.str());
  1663. }
  1664. if (target_filtered_root.size() == 0) {
  1665. if (m_pLogger) {
  1666. stringstream buff;
  1667. buff << m_pcdId << ": line_filter reuslt cluster is empty" ;
  1668. m_pLogger->INFO(buff.str());
  1669. }
  1670. //统计苗数量
  1671. first_row_size = 0;
  1672. for (auto&has_seedling : m_root_center_with_seedling) {
  1673. if (has_seedling>0) { first_row_size += 1; }
  1674. }
  1675. return false;
  1676. }
  1677. if (m_cparam.image_show) {
  1678. std::vector<pcl::PointXYZ> final_box;
  1679. for (auto&pt : target_filtered_root) {
  1680. //扩展矩形范围
  1681. pcl::PointXYZ min_point_aabb_ex;
  1682. pcl::PointXYZ max_point_aabb_ex;
  1683. min_point_aabb_ex.x = pt.x - hole_step_radius;
  1684. min_point_aabb_ex.y = ymin;
  1685. min_point_aabb_ex.z = pt.z - hole_step_radius;
  1686. max_point_aabb_ex.x = pt.x + hole_step_radius;
  1687. max_point_aabb_ex.y = ymax;
  1688. max_point_aabb_ex.z = pt.z + hole_step_radius;
  1689. final_box.push_back(min_point_aabb_ex);
  1690. final_box.push_back(max_point_aabb_ex);
  1691. }
  1692. viewer_cloud_cluster_box(in_cloud, target_filtered_root, final_box, target_member, std::string("line_filter"));
  1693. std::vector<std::vector<int>>target_member_empty;
  1694. viewer_cloud_cluster_box(m_raw_cloud, target_filtered_root, final_box, target_member_empty, std::string("stem_box_in_raw_pc"));
  1695. }
  1696. //保存茎的根部坐标和点云数量
  1697. if (m_pStemInfos) {
  1698. for (size_t k = 0; k < target_filtered_root.size(); ++k) {
  1699. CStemResult sr = CStemResult(target_filtered_root.at(k).x,
  1700. target_filtered_root.at(k).y,
  1701. target_filtered_root.at(k).z,
  1702. target_member.at(k).size(),
  1703. m_pcdId,
  1704. 1);
  1705. m_pStemInfos->append(sr);
  1706. }
  1707. }
  1708. //sort cluster center, get the frontest leftest one
  1709. //找最小z,然后计算平均z
  1710. float mean_root_z_all = 0.0;
  1711. for(auto&pt : target_filtered_root) {
  1712. mean_root_z_all += pt.z;
  1713. }
  1714. mean_root_z_all /= target_filtered_root.size();
  1715. //通过最小z,保守的找到和他一排的植株
  1716. std::vector<int> first_row_index;
  1717. float mean_z = 0.0;
  1718. for (int idx_r = 0; idx_r < target_filtered_root.size();++idx_r) {
  1719. pcl::PointXYZ&pt = target_filtered_root.at(idx_r);
  1720. if (std::fabs(pt.z - mean_root_z_all) < hole_step_radius) {
  1721. first_row_index.push_back(idx_r);
  1722. mean_z += pt.z;
  1723. }
  1724. }
  1725. if (m_pLogger) {
  1726. stringstream buff;
  1727. buff << m_pcdId << ": current seedling number:"<< first_row_index.size()
  1728. <<", mean_z:"<< mean_z;
  1729. m_pLogger->INFO(buff.str());
  1730. }
  1731. //如果第一排的植株大于3,计算平均值
  1732. float first_row_num = (float)first_row_index.size();
  1733. mean_z /= first_row_num;
  1734. if (first_row_num >= 4) {
  1735. if (m_dtype == 0) {
  1736. m_1st_row_zmean_sc = mean_z;
  1737. }
  1738. else{ m_1st_row_zmean_rs = mean_z; }
  1739. }
  1740. else {
  1741. if( m_dtype == 0) {
  1742. if (m_1st_row_zmean_sc > 0) {
  1743. mean_z = m_1st_row_zmean_sc; }
  1744. }
  1745. else {
  1746. if (m_1st_row_zmean_rs > 0) {
  1747. mean_z = m_1st_row_zmean_rs; }
  1748. }
  1749. if (m_pLogger) {
  1750. stringstream buff;
  1751. buff << m_pcdId << ": update with historic mean_z:" << mean_z;
  1752. m_pLogger->INFO(buff.str());
  1753. }
  1754. }
  1755. //通过mean_z再次寻找第一排的植株
  1756. first_row_index.clear();
  1757. for (int idx_r = 0; idx_r < target_filtered_root.size(); ++idx_r) {
  1758. pcl::PointXYZ&pt = target_filtered_root.at(idx_r);
  1759. if (std::fabs(pt.z - mean_z) < hole_step_radius) {
  1760. first_row_index.push_back(idx_r);
  1761. }
  1762. }
  1763. //找第一排的植株没有满足要求的
  1764. if (first_row_index.size()==0) {
  1765. if (m_pLogger) {
  1766. stringstream buff;
  1767. buff << m_pcdId << ": NOT found valid seedlings";
  1768. m_pLogger->INFO(buff.str());
  1769. }
  1770. //统计苗数量
  1771. first_row_size = 0;
  1772. for (auto&has_seedling : m_root_center_with_seedling) {
  1773. if (has_seedling>0) { first_row_size += 1; }
  1774. }
  1775. return false;
  1776. }
  1777. ///////////////////////////////////////////////////////////
  1778. std::vector<float> cluster_index;
  1779. for (int i=0; i<first_row_index.size();++i){
  1780. int raw_idx = first_row_index.at(i);
  1781. pcl::PointXYZ&pt = target_filtered_root.at(raw_idx);
  1782. cluster_index.push_back(pt.x);
  1783. //update m_root_center_with_seedling
  1784. double min_dist = hole_step;
  1785. int min_i = -1;
  1786. for (int rc_i = 0; rc_i < m_root_centers.size(); ++rc_i)
  1787. {
  1788. double dist = fabs(pt.x - m_root_centers.at(rc_i).root_x);
  1789. if (dist < min_dist) {
  1790. min_dist = dist;
  1791. min_i = rc_i;
  1792. }
  1793. }
  1794. if (min_i >= 0) {
  1795. m_root_center_with_seedling.at(min_i) = 1;
  1796. }
  1797. }
  1798. //统计苗数量
  1799. first_row_size = 0;
  1800. for (auto&has_seedling : m_root_center_with_seedling) {
  1801. if (has_seedling>0) { first_row_size += 1; }
  1802. }
  1803. int first_idx = std::min_element(cluster_index.begin(), cluster_index.end()) - cluster_index.begin();
  1804. if (m_dtype == 0) {
  1805. first_idx = std::max_element(cluster_index.begin(), cluster_index.end()) - cluster_index.begin();
  1806. }
  1807. first_idx = first_row_index.at(first_idx);
  1808. first_seedling_cloud_idx.clear();
  1809. for (auto&v : target_member.at(first_idx)) {
  1810. first_seedling_cloud_idx.push_back(v);
  1811. }
  1812. xz_center.x = target_filtered_root.at(first_idx).x;
  1813. xz_center.y = target_filtered_root.at(first_idx).y;
  1814. xz_center.z = target_filtered_root.at(first_idx).z;
  1815. line_model = target_filtered_models.at(first_idx);
  1816. if (m_pLogger) {
  1817. stringstream buff;
  1818. buff << m_pcdId << ": euclidean_clustering_ttsas, find cluster center(" << xz_center.x
  1819. <<", "<< xz_center.y<<", "<< xz_center.z<<")";
  1820. m_pLogger->INFO(buff.str());
  1821. }
  1822. return true;
  1823. }
  1824. void CRootStockGrabPoint::tilted_seedling_discover(
  1825. std::vector<pcl::PointXYZ>&cluster_center, //输入,已知的苗的坐标
  1826. std::vector<pcl::PointXYZ>&tilted_center //输出,有倾斜苗的坐标
  1827. )
  1828. {
  1829. tilted_center.clear();
  1830. if (cluster_center.size() == 0) { return; }
  1831. //找到z最小的那一株,并找出和它一排的那些
  1832. float step_harf = m_cparam.rs_grab_seedling_dist / 2.0;
  1833. float xmin = m_cparam.rs_grab_xmin;
  1834. float xmax = m_cparam.rs_grab_xmax;
  1835. float zmin = m_cparam.rs_grab_zmin;
  1836. float zmax = m_cparam.rs_grab_zmax;
  1837. if (m_dtype == 0) {
  1838. step_harf = m_cparam.sc_grab_seedling_dist / 2.0;
  1839. xmin = m_cparam.sc_grab_xmin;
  1840. xmax = m_cparam.sc_grab_xmax;
  1841. zmin = m_cparam.sc_grab_zmin;
  1842. zmax = m_cparam.sc_grab_zmax;
  1843. }
  1844. auto minz_it = std::min_element(cluster_center.begin(), cluster_center.end(),
  1845. [](const pcl::PointXYZ& p1, const pcl::PointXYZ& p2)-> bool {return p1.z < p2.z; });
  1846. float minz = minz_it->z;
  1847. float meanz = 0.0;
  1848. float cnt = 0.0;
  1849. for (auto&p : cluster_center) {
  1850. if (fabs(p.z - minz) < step_harf) { meanz += p.z; cnt += 1.0; }
  1851. }
  1852. if(cnt>0.0){meanz /= cnt;}
  1853. else { meanz = minz; }
  1854. // 生成所有可能的植株位置中心点
  1855. std::vector<pcl::PointXYZ>candidate_centers;
  1856. for (int row = -1; row <= 1; row += 1) {
  1857. for (int col = -6; col <= 6; col += 1) {
  1858. float cx = minz_it->x + col * 2.0 * step_harf;
  1859. float cz = meanz + row * 2.0 * step_harf;
  1860. if (cx < xmin || cx > xmax) { continue; }
  1861. if (cz < zmin || cz > zmax) { continue; }
  1862. // 邻域内已经存在植株的跳过
  1863. bool with_seedling = false;
  1864. for (auto&p : cluster_center) {
  1865. float d = std::sqrt((p.x - cx) * (p.x - cx) + (p.z - cz) * (p.z - cz));
  1866. if (d < 2.0*step_harf) {
  1867. with_seedling=true;
  1868. break;
  1869. }
  1870. }
  1871. if (!with_seedling) {//保存
  1872. pcl::PointXYZ pc(cx,0.0,cz);
  1873. candidate_centers.push_back(pc);
  1874. }
  1875. }
  1876. }
  1877. //针对每一个candidat_centers的邻域进行检查,检测是否有茎目标
  1878. for (auto&pc : candidate_centers) {
  1879. }
  1880. }
  1881. void CRootStockGrabPoint::find_seedling_position(
  1882. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud,
  1883. std::vector<int> &first_seedling_cloud_idx,
  1884. pcl::PointXYZ&xz_center
  1885. )
  1886. {
  1887. // 确定植株inbox范围
  1888. float hole_step = m_cparam.rs_grab_seedling_dist - 10.0; //穴盘中穴间距
  1889. if (m_dtype == 0) {
  1890. hole_step = m_cparam.sc_grab_seedling_dist - 10.0;
  1891. }
  1892. float hole_step_radius = hole_step / 2.0;
  1893. // 点云降维到xz平面,y=0
  1894. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2d(new pcl::PointCloud < pcl::PointXYZ>);
  1895. pcl::copyPointCloud(*in_cloud, *cloud2d);
  1896. for (auto&pt : *cloud2d) {
  1897. pt.y = 0.0;
  1898. }
  1899. /*if(m_cparam.image_show){
  1900. viewer_cloud(cloud2d, std::string("cloud2d"));
  1901. } */
  1902. // 在xz平面内统计点的密度
  1903. double radius = m_cparam.rs_grab_stem_diameter;
  1904. if (m_dtype == 0) {
  1905. radius = m_cparam.sc_grab_stem_diameter;
  1906. }
  1907. std::vector<int> counter;
  1908. pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
  1909. kdtree.setInputCloud(cloud2d);
  1910. std::vector<int>idx;
  1911. std::vector<float>dist_sqr;
  1912. for (size_t i = 0; i < cloud2d->points.size(); ++i) {
  1913. int k = kdtree.radiusSearch(cloud2d->points.at(i), radius, idx, dist_sqr);
  1914. counter.push_back(k);
  1915. }
  1916. // 计算根据密度分割的自动阈值
  1917. int th = (int)(otsu(counter));
  1918. // 得到茎目标的点云序号,和对应的点云cloud2d_pos
  1919. std::vector<int> index;
  1920. for (size_t i = 0; i < counter.size(); ++i) {
  1921. if (counter.at(i) >= th) {
  1922. index.push_back(i);
  1923. }
  1924. }
  1925. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2d_pos(new pcl::PointCloud < pcl::PointXYZ>);
  1926. pcl::copyPointCloud(*cloud2d, index, *cloud2d_pos);
  1927. if (m_pLogger) {
  1928. stringstream buff;
  1929. buff << m_pcdId <<": get 2d seedling seed point cloud " << index.size() << " data points with thrreshold " << th;
  1930. m_pLogger->INFO(buff.str());
  1931. }
  1932. if (m_cparam.image_show) {
  1933. viewer_cloud(cloud2d_pos, std::string("cloud2d_pos"));
  1934. }
  1935. //对茎的点云进行clustering,得到不同的茎的分组
  1936. double d1 = m_cparam.rs_grab_stem_diameter;
  1937. double d2 = m_cparam.rs_grab_stem_diameter * 3.0;
  1938. if (m_dtype == 0) {
  1939. d1 = m_cparam.sc_grab_stem_diameter;
  1940. d2 = m_cparam.sc_grab_stem_diameter * 3.0;
  1941. }
  1942. std::vector<pcl::PointXYZ>cluster_center;
  1943. std::vector<std::vector<int>> cluster_member;
  1944. euclidean_clustering_ttsas(cloud2d_pos, d1, d2, cluster_center, cluster_member);
  1945. if (m_pLogger) {
  1946. stringstream buff;
  1947. buff << m_pcdId <<": euclidean_clustering_ttsas: " << cluster_center.size() << " t1=" << d1
  1948. << " t2=" << d2;
  1949. m_pLogger->INFO(buff.str());
  1950. }
  1951. if (m_cparam.image_show) {
  1952. pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_cluster(new pcl::PointCloud<pcl::PointXYZRGB>);
  1953. pcl::copyPointCloud(*cloud2d_pos, *cloud_cluster);
  1954. for (auto& pt : *cloud_cluster) {
  1955. pt.r = 255;
  1956. pt.g = 255;
  1957. pt.b = 255;
  1958. }
  1959. viewer_cloud_cluster(cloud_cluster, cluster_center, std::string("cloud2d_cluster_pos"));
  1960. }
  1961. // 扩展检测第一排的可能位置,找到倾斜的苗
  1962. std::vector<pcl::PointXYZ> tilted_center;
  1963. tilted_seedling_discover(cluster_center, tilted_center);
  1964. //对每个类别进行检测,剔除不是茎的类别
  1965. std::vector<pcl::PointXYZ> clt_root;
  1966. std::vector<pcl::PointXYZ> clt_box;
  1967. std::vector<std::vector<int> > clt_line_idx;
  1968. for (size_t i = 0; i < cluster_center.size(); ++i) {
  1969. pcl::PointIndices cluster_idxs;
  1970. for (auto idx_clt : cluster_member.at(i)) {
  1971. int idx_raw = index.at(idx_clt);
  1972. cluster_idxs.indices.push_back(idx_raw);
  1973. }
  1974. pcl::PointCloud<pcl::PointXYZ>::Ptr clt_cloud(new pcl::PointCloud < pcl::PointXYZ>);
  1975. pcl::copyPointCloud(*in_cloud, cluster_idxs, *clt_cloud);
  1976. //计算每一个茎的外接矩形
  1977. pcl::PointXYZ min_point_aabb;
  1978. pcl::PointXYZ max_point_aabb;
  1979. pcl::MomentOfInertiaEstimation<pcl::PointXYZ> feature_extractor;
  1980. feature_extractor.setInputCloud(clt_cloud);
  1981. feature_extractor.compute();
  1982. feature_extractor.getAABB(min_point_aabb, max_point_aabb);
  1983. //扩展矩形范围
  1984. pcl::PointXYZ min_point_aabb_ex;
  1985. pcl::PointXYZ max_point_aabb_ex;
  1986. min_point_aabb_ex.x = 0.5*(min_point_aabb.x + max_point_aabb.x) - hole_step_radius;
  1987. min_point_aabb_ex.y = m_cparam.sc_grab_ymin;
  1988. if (m_dtype != 0) { min_point_aabb_ex.y = m_cparam.rs_grab_ymin; }
  1989. min_point_aabb_ex.z = 0.5*(min_point_aabb.z + max_point_aabb.z) - hole_step_radius;
  1990. max_point_aabb_ex.x = 0.5*(min_point_aabb.x + max_point_aabb.x) + hole_step_radius;
  1991. max_point_aabb_ex.y = m_cparam.sc_grab_ymax;
  1992. if (m_dtype != 0) { max_point_aabb_ex.y = m_cparam.rs_grab_ymax; }
  1993. max_point_aabb_ex.z = 0.5*(min_point_aabb.z + max_point_aabb.z) + hole_step_radius;
  1994. /////////////////////////////////
  1995. //扩展矩形内直线检测
  1996. std::vector<int>line_idx;
  1997. find_line_in_cube(in_cloud, min_point_aabb_ex, max_point_aabb_ex, line_idx);
  1998. clt_line_idx.push_back(line_idx);
  1999. //找到line_idx中y最小的那个点的idx
  2000. int line_root_idx = -1;
  2001. float line_root_y_min = 10000.0;
  2002. for (size_t lidx = 0; lidx < line_idx.size(); ++lidx) {
  2003. int raw_idx = line_idx.at(lidx);
  2004. if (in_cloud->at(raw_idx).y < line_root_y_min) {
  2005. line_root_y_min = in_cloud->at(raw_idx).y;
  2006. line_root_idx = raw_idx;
  2007. }
  2008. }
  2009. //找到底部中心点,然后找到根部坐标
  2010. pcl::PointXYZ pt_root;
  2011. pt_root = in_cloud->at(line_root_idx);
  2012. clt_root.push_back(pt_root);
  2013. clt_box.push_back(min_point_aabb_ex);
  2014. clt_box.push_back(max_point_aabb_ex);
  2015. //viewer_cloud(clt_cloud, std::string("cluster"));
  2016. }
  2017. if (m_cparam.image_show) {
  2018. viewer_cloud_cluster_box(in_cloud, clt_root, clt_box, clt_line_idx, std::string("cloud2d_cluster_box"));
  2019. }
  2020. //sort cluster center, get the frontest leftest one
  2021. std::vector<float> cluster_index;
  2022. for (auto&pt : clt_root) {
  2023. float idx = pt.x - pt.z;
  2024. cluster_index.push_back(idx);
  2025. }
  2026. int first_idx = std::min_element(cluster_index.begin(), cluster_index.end()) - cluster_index.begin();
  2027. if (m_dtype == 0) {
  2028. first_idx = std::max_element(cluster_index.begin(), cluster_index.end()) - cluster_index.begin();
  2029. }
  2030. first_seedling_cloud_idx.clear();
  2031. for (auto&v : clt_line_idx.at(first_idx)) {
  2032. first_seedling_cloud_idx.push_back(v);
  2033. }
  2034. xz_center.x = clt_root.at(first_idx).x;
  2035. xz_center.y = clt_root.at(first_idx).y;
  2036. xz_center.z = clt_root.at(first_idx).z;
  2037. if (m_pLogger) {
  2038. stringstream buff;
  2039. buff << m_pcdId <<": euclidean_clustering_ttsas, find cluster center(" << xz_center.x
  2040. << ", " << xz_center.y << ", " << xz_center.z << ")";
  2041. m_pLogger->INFO(buff.str());
  2042. }
  2043. }
  2044. void CRootStockGrabPoint::find_line_in_cube(
  2045. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //输入,整体点云
  2046. pcl::PointXYZ& min_pt_ex, //输入,
  2047. pcl::PointXYZ& max_pt_ex, //输入,
  2048. std::vector<int>& out_idx //输出,直线上点的index, 基于输入整体点云
  2049. )
  2050. {
  2051. out_idx.clear();
  2052. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  2053. pcl::CropBox<pcl::PointXYZ> box_filter;
  2054. std::vector<int>inbox_idx;
  2055. box_filter.setMin(Eigen::Vector4f(min_pt_ex.x, min_pt_ex.y, min_pt_ex.z, 1));
  2056. box_filter.setMax(Eigen::Vector4f(max_pt_ex.x, max_pt_ex.y, max_pt_ex.z, 1));
  2057. box_filter.setNegative(false);
  2058. box_filter.setInputCloud(in_cloud);
  2059. box_filter.filter(inbox_idx);
  2060. pcl::copyPointCloud(*in_cloud, inbox_idx, *cloud_inbox);
  2061. //找到inbox点云中的直线
  2062. float stem_radius = m_cparam.rs_grab_stem_diameter / 2.0;
  2063. if (m_dtype == 0) {
  2064. stem_radius = m_cparam.sc_grab_stem_diameter / 2.0;
  2065. }
  2066. pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
  2067. pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
  2068. pcl::SACSegmentation<pcl::PointXYZ> seg;
  2069. seg.setOptimizeCoefficients(true);
  2070. seg.setModelType(pcl::SACMODEL_LINE);
  2071. seg.setDistanceThreshold(stem_radius);
  2072. seg.setInputCloud(cloud_inbox);
  2073. seg.segment(*inliers, *coefficients);
  2074. int idx_raw = 0;
  2075. for (auto& idx : inliers->indices) {
  2076. idx_raw = inbox_idx.at(idx);
  2077. out_idx.push_back(idx_raw);
  2078. }
  2079. if (m_cparam.image_show) {
  2080. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_line(new pcl::PointCloud<pcl::PointXYZ>);
  2081. pcl::copyPointCloud(*cloud_inbox, *inliers, *cloud_line);
  2082. pcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer("line in cluster"));
  2083. viewer->addPointCloud<pcl::PointXYZ>(cloud_inbox, "cluster");
  2084. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "cluster");
  2085. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cluster");
  2086. viewer->addPointCloud(cloud_line, "fit_line");
  2087. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0, 1, 0, "fit_line");
  2088. viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "fit_line");
  2089. while (!viewer->wasStopped()) {
  2090. viewer->spinOnce(100);
  2091. }
  2092. }
  2093. }
  2094. void CRootStockGrabPoint::crop_nn_analysis(
  2095. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud,
  2096. pcl::PointCloud<pcl::PointXYZ>::Ptr seed_cloud,
  2097. double dist_mean,
  2098. std::vector<double>&mass_indices,
  2099. std::vector<int>& candidate_idx
  2100. )
  2101. {
  2102. candidate_idx.clear();
  2103. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  2104. pcl::CropBox<pcl::PointXYZ> box_filter;
  2105. box_filter.setNegative(false);
  2106. box_filter.setInputCloud(in_cloud);
  2107. double radius = 5;
  2108. double rx = 0.8;
  2109. double ry = 1.0;
  2110. double rz = 0.8;
  2111. double cx, cy, cz;
  2112. double dz;
  2113. for (size_t i = 0; i < seed_cloud->points.size(); ++i) {
  2114. cx = seed_cloud->points.at(i).x;
  2115. cy = seed_cloud->points.at(i).y;
  2116. cz = seed_cloud->points.at(i).z;
  2117. box_filter.setMin(Eigen::Vector4f(cx - rx*radius, cy - ry*radius, cz - rz*radius, 1));
  2118. box_filter.setMax(Eigen::Vector4f(cx + rx*radius, cy + ry*radius, cz + rz*radius, 1));
  2119. box_filter.filter(*cloud_inbox);
  2120. //dz
  2121. Eigen::Vector4f min_point;
  2122. Eigen::Vector4f max_point;
  2123. pcl::getMinMax3D(*cloud_inbox, min_point, max_point);
  2124. dz = max_point(2) - min_point(2);
  2125. //project to xy-plane
  2126. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox_xy(new pcl::PointCloud<pcl::PointXYZ>);
  2127. pcl::copyPointCloud(*cloud_inbox, *cloud_inbox_xy);
  2128. for (auto&pt : *cloud_inbox_xy) { pt.z = 0.0; }
  2129. //pca
  2130. double dx_obb;
  2131. double dy_obb;
  2132. double angle_obb;
  2133. cal_obb_2d(cloud_inbox_xy, 0, dx_obb, dy_obb, angle_obb);
  2134. try {
  2135. double dx_grid = dx_obb / dist_mean;
  2136. double dy_grid = dy_obb / dist_mean;
  2137. double dz_grid = dz / dist_mean;
  2138. double fill_ratio = cloud_inbox->points.size() / dx_grid / dy_grid / dz_grid;
  2139. double y_ratio = dy_obb / dx_obb/2;
  2140. y_ratio = pow(y_ratio, 2);
  2141. double a_ratio = cos((angle_obb - 90)*PI / 180.0);
  2142. a_ratio = pow(a_ratio, 3);
  2143. double mass_index = fill_ratio*y_ratio*a_ratio;
  2144. mass_indices.push_back(mass_index);
  2145. if (m_pLogger) {
  2146. stringstream buff;
  2147. buff << i << "/" << seed_cloud->points.size() << " dx=" << dx_obb << ", dy=" << dy_obb << ", fill_ratio=" << fill_ratio
  2148. << ", y_ratio=" << y_ratio << ", a_ratio=" << a_ratio << ", mass_index=" << mass_index;
  2149. m_pLogger->INFO(buff.str());
  2150. }
  2151. }
  2152. catch (...) {
  2153. mass_indices.push_back(0);
  2154. }
  2155. }
  2156. // sort by mass_indices
  2157. std::vector<size_t> sort_idx = sort_indexes_e(mass_indices, false);
  2158. for (auto&v : sort_idx) { candidate_idx.push_back((int)v); }
  2159. }
  2160. void CRootStockGrabPoint::euclidean_clustering_ttsas(
  2161. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud,
  2162. double d1, double d2,
  2163. std::vector<pcl::PointXYZ>&cluster_center,
  2164. std::vector<std::vector<int>> &clustr_member
  2165. )
  2166. {
  2167. if (m_pLogger) {
  2168. stringstream buff;
  2169. buff << m_pcdId <<": euclidean_clustering_ttsas() begin...";
  2170. m_pLogger->INFO(buff.str());
  2171. }
  2172. std::vector<int> cluster_weight;
  2173. std::vector<int> data_stat;
  2174. std::vector<pcl::PointXYZ>cluster_center_raw;
  2175. std::vector<std::vector<int>> clustr_member_raw;
  2176. for (size_t i = 0; i < in_cloud->points.size(); ++i) { data_stat.push_back(0); }
  2177. size_t data_len = in_cloud->points.size();
  2178. int exists_change = 0;
  2179. int prev_change = 0;
  2180. int cur_change = 0;
  2181. int m = 0;
  2182. while (std::find(data_stat.begin(), data_stat.end(), 0) != data_stat.end()) {
  2183. bool new_while_first = true;
  2184. for (size_t i = 0; i < data_len; ++i) {
  2185. if (data_stat.at(i) == 0 && new_while_first && exists_change == 0) {
  2186. new_while_first = false;
  2187. std::vector<int> idx;
  2188. idx.push_back(i);
  2189. clustr_member_raw.push_back(idx);
  2190. pcl::PointXYZ center;
  2191. center.x = in_cloud->points.at(i).x;
  2192. center.y = in_cloud->points.at(i).y;
  2193. center.z = in_cloud->points.at(i).z;
  2194. cluster_center_raw.push_back(center);
  2195. data_stat.at(i) = 1;
  2196. cur_change += 1;
  2197. cluster_weight.push_back(1);
  2198. m += 1;
  2199. }
  2200. else if (data_stat[i] == 0) {
  2201. std::vector<float> distances;
  2202. for (size_t j = 0; j < clustr_member_raw.size(); ++j) {
  2203. std::vector<float> distances_sub;
  2204. for (size_t jj = 0; jj < clustr_member_raw.at(j).size(); ++jj) {
  2205. size_t ele_idx = clustr_member_raw.at(j).at(jj);
  2206. double d = sqrt(
  2207. (in_cloud->points.at(i).x - in_cloud->points.at(ele_idx).x) * (in_cloud->points.at(i).x - in_cloud->points.at(ele_idx).x) +
  2208. (in_cloud->points.at(i).y - in_cloud->points.at(ele_idx).y) * (in_cloud->points.at(i).y - in_cloud->points.at(ele_idx).y) +
  2209. (in_cloud->points.at(i).z - in_cloud->points.at(ele_idx).z) * (in_cloud->points.at(i).z - in_cloud->points.at(ele_idx).z));
  2210. distances_sub.push_back(d);
  2211. }
  2212. double min_dist = *std::min_element(distances_sub.begin(), distances_sub.end());
  2213. distances.push_back(min_dist);
  2214. }
  2215. int min_idx = std::min_element(distances.begin(), distances.end()) - distances.begin();
  2216. if (distances.at(min_idx) < d1) {
  2217. data_stat.at(i) = 1;
  2218. double w = cluster_weight.at(min_idx);
  2219. cluster_weight.at(min_idx) += 1;
  2220. clustr_member_raw.at(min_idx).push_back(i);
  2221. cluster_center_raw.at(min_idx).x = (cluster_center_raw.at(min_idx).x * w + in_cloud->points.at(i).x) / (w + 1);
  2222. cluster_center_raw.at(min_idx).y = (cluster_center_raw.at(min_idx).y * w + in_cloud->points.at(i).y) / (w + 1);
  2223. cluster_center_raw.at(min_idx).z = (cluster_center_raw.at(min_idx).z * w + in_cloud->points.at(i).z) / (w + 1);
  2224. cur_change += 1;
  2225. }
  2226. else if (distances.at(min_idx) > d2) {
  2227. std::vector<int> idx;
  2228. idx.push_back(i);
  2229. clustr_member_raw.push_back(idx);
  2230. pcl::PointXYZ center;
  2231. center.x = in_cloud->points.at(i).x;
  2232. center.y = in_cloud->points.at(i).y;
  2233. center.z = in_cloud->points.at(i).z;
  2234. cluster_center_raw.push_back(center);
  2235. data_stat.at(i) = 1;
  2236. cur_change += 1;
  2237. cluster_weight.push_back(1);
  2238. m += 1;
  2239. }
  2240. }
  2241. else if (data_stat.at(i)== 1) {
  2242. cur_change += 1;
  2243. }
  2244. }
  2245. exists_change = fabs(cur_change - prev_change);
  2246. prev_change = cur_change;
  2247. cur_change = 0;
  2248. }
  2249. // copy result
  2250. for (size_t i = 0; i < clustr_member_raw.size(); ++i) {
  2251. if (clustr_member_raw.at(i).size() < 20) { continue; }
  2252. cluster_center.push_back(cluster_center_raw.at(i));
  2253. clustr_member.push_back(clustr_member_raw.at(i));
  2254. }
  2255. if (m_pLogger) {
  2256. stringstream buff;
  2257. buff << m_pcdId <<": euclidean_clustering_ttsas() end";
  2258. m_pLogger->INFO(buff.str());
  2259. }
  2260. }
  2261. void CRootStockGrabPoint::cal_obb_2d(
  2262. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud,
  2263. int axis, //0--xy, 1--zy
  2264. double &dx_obb,
  2265. double &dy_obb,
  2266. double &angle_obb
  2267. )
  2268. {
  2269. // asign value
  2270. Eigen::MatrixXd pts(in_cloud->points.size(), 2);
  2271. for (size_t i = 0; i < in_cloud->points.size(); ++i) {
  2272. if (axis == 0) {
  2273. pts(i, 0) = in_cloud->points.at(i).x;
  2274. }
  2275. else {
  2276. pts(i, 0) = in_cloud->points.at(i).z;
  2277. }
  2278. pts(i, 1) = in_cloud->points.at(i).y;
  2279. }
  2280. // centerlize
  2281. Eigen::MatrixXd mu = pts.colwise().mean();
  2282. Eigen::RowVectorXd mu_row = mu;
  2283. pts.rowwise() -= mu_row;
  2284. //calculate covariance
  2285. Eigen::MatrixXd C = pts.adjoint()*pts;
  2286. C = C.array() / (pts.cols() - 1);
  2287. //compute eig
  2288. Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(C);
  2289. Eigen::MatrixXd d = eig.eigenvalues();
  2290. Eigen::MatrixXd v = eig.eigenvectors();
  2291. //projection
  2292. Eigen::MatrixXd p = pts * v;
  2293. Eigen::VectorXd minv = p.colwise().minCoeff();
  2294. Eigen::VectorXd maxv = p.colwise().maxCoeff();
  2295. Eigen::VectorXd range = maxv - minv;
  2296. dy_obb = range(1);
  2297. dx_obb = range(0);
  2298. angle_obb = std::atan2(v(1, 1), v(0, 1));
  2299. if (angle_obb < 0) { angle_obb = PI + angle_obb; }
  2300. angle_obb = angle_obb * 180 / PI;
  2301. }
  2302. void CRootStockGrabPoint::get_optimal_seed_compare(
  2303. pcl::PointCloud<pcl::PointXYZ>::Ptr in_cloud, //input 全部有效点云
  2304. pcl::PointCloud<pcl::PointXYZ>::Ptr in_line_cloud, //input 茎上直线点云
  2305. pcl::ModelCoefficients::Ptr line_model, //input
  2306. pcl::PointXYZ&pt, // 返回抓取的点坐标,基于pt_ref的偏移点
  2307. pcl::PointXYZ &pt_ref, // 返回点茎节的参考点
  2308. pcl::PointXYZ&pt_rs_grab, // 返回砧木指定的固定高度位置坐标
  2309. std::vector<float>& fork_ys, // 返回,fork y的高度
  2310. float& stem_width_mu, // 茎宽度,直径
  2311. float& stem_deflection //茎的最大挠度,最大弯曲处的偏离直径轴心的距离,毫米
  2312. )
  2313. {
  2314. pt.x = -1000.0;
  2315. pt.y = -1000.0;
  2316. pt.z = -1000.0;
  2317. pt_ref.x = -1000.0;
  2318. pt_ref.y = -1000.0;
  2319. pt_ref.z = -1000.0;
  2320. pt_rs_grab.x = -1000.0;
  2321. pt_rs_grab.y = -1000.0;
  2322. pt_rs_grab.z = -1000.0;
  2323. fork_ys.clear();
  2324. stem_width_mu = 0.0;
  2325. stem_deflection = 0.0;
  2326. float ymin, ymax;
  2327. ymin = m_cparam.rs_grab_ymin;
  2328. ymax = m_cparam.rs_grab_ymax;
  2329. float radius = m_cparam.rs_grab_stem_diameter;
  2330. if (m_dtype == 0) {
  2331. ymin = m_cparam.sc_grab_ymin;
  2332. ymax = m_cparam.sc_grab_ymax;
  2333. radius = m_cparam.sc_grab_stem_diameter;
  2334. }
  2335. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  2336. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox_line(new pcl::PointCloud<pcl::PointXYZ>);
  2337. std::vector<float> stem_width;
  2338. std::vector<pcl::PointXYZ>online_points;
  2339. pcl::CropBox<pcl::PointXYZ> box_filter;
  2340. box_filter.setNegative(false);
  2341. box_filter.setInputCloud(in_cloud);
  2342. pcl::CropBox<pcl::PointXYZ> box_filter_line;
  2343. box_filter_line.setNegative(false);
  2344. box_filter_line.setInputCloud(in_line_cloud);
  2345. float cx, cy, cz, t;
  2346. float rx = 1.05;
  2347. float ry = 1.05;
  2348. float rz = 1.05;
  2349. float dz, dx;
  2350. cy = ymin;
  2351. //计算茎上的直径
  2352. while(cy<ymax){
  2353. t = (cy - line_model->values.at(1)) / line_model->values.at(4);
  2354. cx = line_model->values.at(3) * t + line_model->values.at(0);
  2355. cz = line_model->values.at(5) * t + line_model->values.at(2);
  2356. //////////////////////////////////////////////////////////////////
  2357. //原始点云,获取指定区域的dx,dz
  2358. box_filter.setMin(Eigen::Vector4f(cx - rx*radius, cy - 2, cz - rz*radius, 1));
  2359. box_filter.setMax(Eigen::Vector4f(cx + rx*radius, cy + 2, cz + rz*radius, 1));
  2360. box_filter.filter(*cloud_inbox);
  2361. if (cloud_inbox->points.size() > 10) {
  2362. Eigen::Vector4f min_point;
  2363. Eigen::Vector4f max_point;
  2364. pcl::getMinMax3D(*cloud_inbox, min_point, max_point);
  2365. dx = max_point(0) - min_point(0);
  2366. stem_width.push_back(dx);
  2367. }
  2368. else {
  2369. stem_width.push_back(0);
  2370. }
  2371. pcl::PointXYZ tmp_pt(cx,cy,cz);
  2372. online_points.push_back(tmp_pt);
  2373. cy += 1.0;
  2374. }
  2375. //得到有效直径数值,并计算均值、标准差
  2376. std::vector<float>valid_stem_width;
  2377. for (auto&w : stem_width) {
  2378. if (w > 0) {
  2379. valid_stem_width.push_back(w);
  2380. }
  2381. }
  2382. float mu = get_hist_mean(valid_stem_width);
  2383. float stdv = get_hist_std(valid_stem_width, mu);
  2384. //找到茎节
  2385. std::vector<int> fork_positions;
  2386. find_fork(in_line_cloud, line_model, mu, stem_width, fork_positions, stem_width_mu);
  2387. for (auto&y : fork_positions) {
  2388. fork_ys.push_back(y + ymin);
  2389. }
  2390. stem_deflection = static_cast<float>(calculate_deflection(in_line_cloud, line_model));
  2391. //4 用茎节上下限高度值进行约束,如果超限,用最低限高度作为茎节高度
  2392. double grab_fork_yup = m_cparam.rs_grab_fork_yup;
  2393. double grab_fork_ybt = m_cparam.rs_grab_fork_ybt;
  2394. if (m_dtype == 0) {
  2395. grab_fork_yup = m_cparam.sc_grab_fork_yup;
  2396. grab_fork_ybt = m_cparam.sc_grab_fork_ybt;
  2397. }
  2398. float z_mu = 0.0;
  2399. float x_mu = 0.0;
  2400. Eigen::Vector4f min_point;
  2401. Eigen::Vector4f max_point;
  2402. if (m_dtype == 1) {
  2403. float grab_y = 0.5 * (m_cparam.rs_grab_fork_ybt + m_cparam.rs_grab_fork_yup);
  2404. int grab_y_pos = int(grab_y - m_cparam.rs_grab_ymin);
  2405. cx = online_points.at(grab_y_pos).x;
  2406. cy = online_points.at(grab_y_pos).y;
  2407. cz = online_points.at(grab_y_pos).z;
  2408. box_filter_line.setMin(Eigen::Vector4f(cx - rx*radius, cy - 2, cz - rz*radius, 1));
  2409. box_filter_line.setMax(Eigen::Vector4f(cx + rx*radius, cy + 2, cz + rz*radius, 1));
  2410. box_filter_line.filter(*cloud_inbox_line);
  2411. z_mu = cz;
  2412. x_mu = cx;
  2413. if (cloud_inbox_line->points.size() > 5) {
  2414. pcl::getMinMax3D(*cloud_inbox_line, min_point, max_point);
  2415. z_mu = 0.5 * (max_point(2) + min_point(2));
  2416. x_mu = 0.5 * (max_point(0) + min_point(0));
  2417. }
  2418. pt_rs_grab.x = x_mu;
  2419. pt_rs_grab.y = cy;
  2420. pt_rs_grab.z = z_mu;
  2421. //显示位置
  2422. if (m_cparam.image_show) {
  2423. pcl::visualization::PCLVisualizer viewer("grab line");
  2424. viewer.addCoordinateSystem();
  2425. viewer.addPointCloud<pcl::PointXYZ>(in_line_cloud, "stem_cloud");//????????????????
  2426. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "stem_cloud");
  2427. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "stem_cloud");
  2428. viewer.addLine(online_points.front(), online_points.back(), 1.0, 0.0, 0.0);
  2429. while (!viewer.wasStopped()) {
  2430. viewer.spinOnce(100);
  2431. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  2432. }
  2433. }
  2434. return;
  2435. }
  2436. //穗苗处理
  2437. int max_pos = 0;
  2438. int max_pos_ref = max_pos;
  2439. double offset = 0.0;
  2440. double fork_y = 0.0;
  2441. if (fork_positions.size() == 0) {
  2442. max_pos = 0;
  2443. max_pos_ref = max_pos;
  2444. offset = m_cparam.sc_grab_offset_nofork;
  2445. }
  2446. else {
  2447. max_pos = *std::min_element(fork_positions.begin(), fork_positions.end());
  2448. max_pos_ref = max_pos;
  2449. fork_y = max_pos + ymin;
  2450. if (fork_y > grab_fork_yup) {
  2451. offset = m_cparam.sc_grab_offset_up;
  2452. }
  2453. else {
  2454. if (fork_y < grab_fork_ybt) {
  2455. offset = m_cparam.sc_grab_offset_bt;
  2456. }
  2457. else {
  2458. offset = m_cparam.sc_grab_offset_normal;
  2459. }
  2460. }
  2461. }
  2462. //5 按指定量偏移
  2463. max_pos += static_cast<int>(offset);
  2464. if (max_pos < 0) { max_pos = 0; }
  2465. if (max_pos >= online_points.size()) { max_pos = online_points.size() - 1; }
  2466. /////////////////////////////////////////////////////////////////////
  2467. //直线点云,获取指定区域的dx_line,dz_line
  2468. cx = online_points.at(max_pos).x;
  2469. cy = online_points.at(max_pos).y;
  2470. cz = online_points.at(max_pos).z;
  2471. box_filter_line.setMin(Eigen::Vector4f(cx - rx*radius, cy - 2, cz - rz*radius, 1));
  2472. box_filter_line.setMax(Eigen::Vector4f(cx + rx*radius, cy + 2, cz + rz*radius, 1));
  2473. box_filter_line.filter(*cloud_inbox_line);
  2474. z_mu = cz;
  2475. x_mu = cx;
  2476. if (cloud_inbox_line->points.size() > 5) {
  2477. pcl::getMinMax3D(*cloud_inbox_line, min_point, max_point);
  2478. z_mu = 0.5 * (max_point(2) + min_point(2));
  2479. x_mu = 0.5 * (max_point(0) + min_point(0));
  2480. }
  2481. pt.x = x_mu;
  2482. pt.y = cy;
  2483. pt.z = z_mu;
  2484. pt_ref.x = online_points.at(max_pos_ref).x;
  2485. pt_ref.y = online_points.at(max_pos_ref).y;
  2486. pt_ref.z = online_points.at(max_pos_ref).z;
  2487. //显示位置
  2488. if (m_cparam.image_show) {
  2489. pcl::visualization::PCLVisualizer viewer("grab line");
  2490. viewer.addCoordinateSystem();
  2491. viewer.addPointCloud<pcl::PointXYZ>(in_line_cloud, "stem_cloud");//????????????????
  2492. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "stem_cloud");
  2493. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "stem_cloud");
  2494. viewer.addLine(online_points.front(), online_points.back(), 1.0, 0.0, 0.0);
  2495. while (!viewer.wasStopped()) {
  2496. viewer.spinOnce(100);
  2497. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  2498. }
  2499. }
  2500. }
  2501. //计算茎的弯曲度:点云到直线的距离95分位
  2502. double CRootStockGrabPoint::calculate_deflection(
  2503. pcl::PointCloud<pcl::PointXYZ>::Ptr in_line_cloud, //input
  2504. pcl::ModelCoefficients::Ptr line_model //input
  2505. )
  2506. {
  2507. double deflection = 0.0;
  2508. std::vector<double> dists;
  2509. Eigen::Vector4f line_pt = { line_model->values[0],line_model->values[1],line_model->values[2],0.0 };
  2510. Eigen::Vector4f line_dir = { line_model->values[3],line_model->values[4],line_model->values[5],0.0 };
  2511. for (auto ptc : in_line_cloud->points) {
  2512. //Get the square distance from a point to a line (represented by a point and a direction)
  2513. Eigen::Vector4f pt = { ptc.x, ptc.y, ptc.z, 0.0 };
  2514. double dist = (line_dir.cross3(line_pt - pt)).squaredNorm() / line_dir.squaredNorm();
  2515. dists.push_back(sqrt(dist));
  2516. }
  2517. //deflection = get_hist_mean(dists);
  2518. //95 percentile
  2519. if (dists.size() > 0) {
  2520. int idx_95 = int(0.95 * dists.size());
  2521. std::sort(dists.begin(), dists.end());
  2522. deflection = dists.at(idx_95);
  2523. }
  2524. return deflection;
  2525. }
  2526. void CRootStockGrabPoint::find_fork(
  2527. pcl::PointCloud<pcl::PointXYZ>::Ptr in_line_cloud,
  2528. pcl::ModelCoefficients::Ptr line_model, //输入
  2529. //float& max_dist,
  2530. //int& max_idx,
  2531. float stem_width_ex_mu,//输入, 通过外沿矩形得到的x方向茎粗均值
  2532. const std::vector<float>& stem_width_ex,//输入, 通过外沿矩形得到的x方向茎粗
  2533. std::vector<int>&fork_pos, //输出, 多个fork位置
  2534. float& stem_width_mu //输出, xy投影上x方向的茎粗均值
  2535. )
  2536. {
  2537. fork_pos.clear();
  2538. stem_width_mu = 0.0;
  2539. //1 project to xy plane
  2540. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_line_2d(new pcl::PointCloud<pcl::PointXYZ>);
  2541. pcl::copyPointCloud(*in_line_cloud, *cloud_line_2d);
  2542. for (pcl::PointXYZ&p : cloud_line_2d->points) { p.z = 0.0; }
  2543. //2 边界检测
  2544. pcl::search::KdTree<pcl::PointXYZ>::Ptr kdtree_ptr(new pcl::search::KdTree<pcl::PointXYZ>);
  2545. pcl::PointCloud<pcl::Normal>::Ptr normal(new pcl::PointCloud<pcl::Normal>);
  2546. pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
  2547. ne.setInputCloud(cloud_line_2d);
  2548. ne.setSearchMethod(kdtree_ptr);
  2549. ne.setRadiusSearch(3.0);
  2550. ne.compute(*normal);
  2551. pcl::PointCloud<pcl::Boundary>::Ptr boundaries(new pcl::PointCloud<pcl::Boundary>);
  2552. boundaries->resize(cloud_line_2d->size());
  2553. pcl::BoundaryEstimation < pcl::PointXYZ, pcl::Normal, pcl::Boundary>boundary_estimation;
  2554. boundary_estimation.setInputCloud(cloud_line_2d);
  2555. boundary_estimation.setInputNormals(normal);
  2556. boundary_estimation.setSearchMethod(kdtree_ptr);
  2557. boundary_estimation.setKSearch(30);
  2558. boundary_estimation.setAngleThreshold(M_PI*0.6);
  2559. boundary_estimation.compute(*boundaries);
  2560. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_lines(new pcl::PointCloud<pcl::PointXYZ>);
  2561. pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_visual(new pcl::PointCloud<pcl::PointXYZRGB>);
  2562. cloud_visual->resize(cloud_line_2d->size());
  2563. float dx, xi,xi_hat, yi,t;
  2564. std::vector<int> left_edge_idx, right_edge_idx;
  2565. for (size_t i = 0; i < cloud_line_2d->size(); ++i) {
  2566. cloud_visual->points.at(i).x = cloud_line_2d->points.at(i).x;
  2567. cloud_visual->points.at(i).y = cloud_line_2d->points.at(i).y;
  2568. cloud_visual->points.at(i).z = cloud_line_2d->points.at(i).z;
  2569. if (boundaries->points.at(i).boundary_point != 0) {
  2570. xi = cloud_line_2d->points.at(i).x;
  2571. yi = cloud_line_2d->points.at(i).y;
  2572. t = (yi - line_model->values.at(1)) / line_model->values.at(4);
  2573. xi_hat = line_model->values.at(3) * t + line_model->values.at(0);
  2574. dx = xi - xi_hat;
  2575. cloud_visual->points.at(i).r = 255;
  2576. cloud_visual->points.at(i).b = 0;
  2577. cloud_visual->points.at(i).g = 0;
  2578. if (dx > 0.5) {
  2579. cloud_visual->points.at(i).r = 0;
  2580. cloud_visual->points.at(i).b = 200;
  2581. right_edge_idx.push_back(i);
  2582. }
  2583. if (dx < -0.5) {
  2584. cloud_visual->points.at(i).r = 0;
  2585. cloud_visual->points.at(i).g = 200;
  2586. left_edge_idx.push_back(i);
  2587. }
  2588. cloud_lines->points.push_back(cloud_line_2d->points.at(i));
  2589. }
  2590. else {
  2591. cloud_visual->points.at(i).r = 255;
  2592. cloud_visual->points.at(i).g = 255;
  2593. cloud_visual->points.at(i).b = 255;
  2594. }
  2595. }
  2596. //计算茎左右边缘的直线
  2597. pcl::ModelCoefficients::Ptr edge_line_left(new pcl::ModelCoefficients);
  2598. pcl::ModelCoefficients::Ptr edge_line_right(new pcl::ModelCoefficients);
  2599. get_edge_line(cloud_line_2d, left_edge_idx, edge_line_left);
  2600. get_edge_line(cloud_line_2d, right_edge_idx, edge_line_right);
  2601. pcl::PointXYZ p_left_min, p_left_max, p_right_min, p_right_max;
  2602. stem_width_mu = get_stem_width(edge_line_left, edge_line_right, p_left_min, p_left_max, p_right_min, p_right_max);
  2603. /*if (m_cparam.image_show) {
  2604. viewer_cloud(cloud_visual, string("boundary"));
  2605. viewer_cloud(cloud_lines, string("cloud_lines"));
  2606. }
  2607. */
  2608. //3 find points with max distance to boundaries point
  2609. pcl::search::KdTree<pcl::PointXYZ>::Ptr bound_kdtree_ptr(new pcl::search::KdTree<pcl::PointXYZ>);
  2610. bound_kdtree_ptr->setInputCloud(cloud_lines);
  2611. //构建基于ymin的vector记录每一个毫米中的最大距离边缘的距离
  2612. double ymin = m_cparam.rs_grab_ymin;
  2613. double ymax = m_cparam.rs_grab_ymax;
  2614. double stemd = m_cparam.rs_grab_stem_diameter;
  2615. double th_fork = m_cparam.rs_grab_fork_ratio;
  2616. double th_fork_h = m_cparam.rs_grab_fork_height;
  2617. if (m_dtype == 0) {
  2618. ymin = m_cparam.sc_grab_ymin;
  2619. ymax = m_cparam.sc_grab_ymax;
  2620. stemd = m_cparam.sc_grab_stem_diameter;
  2621. th_fork = m_cparam.sc_grab_fork_ratio;
  2622. th_fork_h = m_cparam.sc_grab_fork_height;
  2623. }
  2624. int length = int(ymax - ymin);
  2625. std::vector<float> stem_diameters;
  2626. stem_diameters.assign(length, 0.0);
  2627. int k = 1;
  2628. for (int i = 0; i < cloud_line_2d->size(); ++i) {
  2629. if (boundaries->points.at(i).boundary_point != 0) { continue; }
  2630. std::vector<int> idx(k);
  2631. std::vector<float> sqr_distances(k);
  2632. int cnt = bound_kdtree_ptr->nearestKSearch(cloud_line_2d->points.at(i), k,idx,sqr_distances);
  2633. if (cnt > 0) {
  2634. float stem_r = sqrt(sqr_distances.at(0));
  2635. int idx = int(cloud_line_2d->points.at(i).y - ymin);
  2636. if (idx >= length) { continue; }
  2637. if (stem_diameters.at(idx) < stem_r) {
  2638. stem_diameters.at(idx) = stem_r;
  2639. }
  2640. }
  2641. }
  2642. //计算平均半径
  2643. float mean_r = 0.0;
  2644. float cnt = 0.0;
  2645. for (auto&r : stem_diameters) {
  2646. if (r > 0.5) {
  2647. //边缘点有可能被遗漏造成半径很小,将很小的半径去除(即小于直径1.0的苗,认为是异常,剔除异常数据)
  2648. mean_r += r;
  2649. cnt += 1.0;
  2650. }
  2651. }
  2652. if (cnt > 0.0) {
  2653. mean_r /= cnt;
  2654. }
  2655. int del_radius = 4;
  2656. int security_r = (int)(stemd / 2.0 + 0.5);//保护半径
  2657. int noise_r = int(stemd); //噪声半径
  2658. std::vector<float> stem_noise;
  2659. calculate_noise(stem_diameters, security_r, noise_r, stem_noise);
  2660. while (true) {
  2661. //找到最大值的位置和最大值
  2662. int midx = max_element(stem_diameters.begin(), stem_diameters.end()) - stem_diameters.begin();
  2663. if (stem_diameters.at(midx) > th_fork * mean_r) {
  2664. //大于周围的值的均值的1.5倍,才能成为茎节
  2665. if (stem_diameters.at(midx) > th_fork * stem_noise.at(midx)) {
  2666. //检测midx附近高于阈值的范围,得到茎节高度
  2667. int minj = 1000;
  2668. int maxj = -1000;
  2669. for (int k = -del_radius; k <= del_radius; ++k) {
  2670. int j = k + midx;
  2671. if (j < 0 || j >= length) {
  2672. continue;
  2673. }
  2674. if (stem_diameters.at(j) <= th_fork * stem_noise.at(midx)) { continue; }
  2675. if (j <= minj) { minj = j; }
  2676. if (j >= maxj) { maxj = j; }
  2677. }
  2678. if (maxj - minj + 1 < th_fork_h) {
  2679. //清除发现的最大直径周围的数据
  2680. for (int k = -del_radius; k <= del_radius; ++k) {
  2681. int j = k + midx;
  2682. if (j < 0 || j >= length) {
  2683. continue;
  2684. }
  2685. stem_diameters.at(j) = 0.0;
  2686. }
  2687. continue;
  2688. }
  2689. //检测fork_pos中的近邻是否存在
  2690. bool has_nn = false;
  2691. for (auto& fy : fork_pos) {
  2692. if (fabs(fy - midx) < 20) {
  2693. has_nn = true;
  2694. break;
  2695. }
  2696. }
  2697. //如果没有近邻存在,保存
  2698. if (!has_nn) {
  2699. fork_pos.push_back(midx);
  2700. }
  2701. }
  2702. //清除发现的最大直径周围的数据
  2703. for (int k = -del_radius; k <= del_radius; ++k) {
  2704. int j = k + midx;
  2705. if (j < 0 || j >= length) {
  2706. continue;
  2707. }
  2708. stem_diameters.at(j) = 0.0;
  2709. }
  2710. }
  2711. else {
  2712. break;
  2713. }
  2714. }
  2715. //再通过stem_width_ex找茎节
  2716. std::vector<float> stem_width_ex_cp(stem_width_ex);
  2717. while (true) {
  2718. //找到最大值的位置和最大值
  2719. int midx = max_element(stem_width_ex_cp.begin(), stem_width_ex_cp.end()) - stem_width_ex_cp.begin();
  2720. if (stem_width_ex_cp.at(midx) > th_fork * stem_width_ex_mu) {
  2721. int minj = 1000;
  2722. int maxj = -1000;
  2723. for (int k = -del_radius; k <= del_radius; ++k) {
  2724. int j = k + midx;
  2725. if (j < 0 || j >= stem_width_ex_cp.size()) {
  2726. continue;
  2727. }
  2728. if (stem_width_ex_cp.at(j) <= th_fork * stem_width_ex_mu) { continue; }
  2729. if (j <= minj) { minj = j; }
  2730. if (j >= maxj) { maxj = j; }
  2731. }
  2732. if (maxj - minj + 1 < th_fork_h) {
  2733. //清除发现的最大直径周围的数据
  2734. for (int k = -del_radius; k <= del_radius; ++k) {
  2735. int j = k + midx;
  2736. if (j < 0 || j >= stem_width_ex_cp.size()) {
  2737. continue;
  2738. }
  2739. stem_width_ex_cp.at(j) = 0.0;
  2740. }
  2741. continue;
  2742. }
  2743. //检测fork_pos中的近邻是否存在
  2744. bool has_nn = false;
  2745. for (auto& fy : fork_pos) {
  2746. if (fabs(fy - midx) < 20) {
  2747. has_nn = true;
  2748. break;
  2749. }
  2750. }
  2751. //如果没有近邻存在,保存
  2752. if (!has_nn) {
  2753. fork_pos.push_back(midx);
  2754. }
  2755. //清除发现的最大直径周围的数据
  2756. for (int k = -del_radius; k <= del_radius; ++k) {
  2757. int j = k + midx;
  2758. if (j < 0 || j >= stem_width_ex_cp.size()) {
  2759. continue;
  2760. }
  2761. stem_width_ex_cp.at(j) = 0.0;
  2762. }
  2763. }
  2764. else {
  2765. break;
  2766. }
  2767. }
  2768. if (m_cparam.image_show) {
  2769. pcl::visualization::PCLVisualizer viewer("boundary line");
  2770. viewer.addCoordinateSystem();
  2771. viewer.addPointCloud<pcl::PointXYZRGB>(cloud_visual, "boundary");
  2772. char buf[8];
  2773. for(auto&h: fork_pos) {
  2774. pcl::PointXYZ p0,p1;
  2775. p0.x = cloud_line_2d->points.at(0).x-5;
  2776. p0.y = ymin + h;
  2777. p0.z = cloud_line_2d->points.at(0).z;
  2778. p1.x = cloud_line_2d->points.at(0).x + 5;
  2779. p1.y = ymin+h;
  2780. p1.z = cloud_line_2d->points.at(0).z;
  2781. viewer.addLine(p0, p1, 1.0, 0.0, 0.0, "fork_y_" + string(_itoa(h, buf, 10)));
  2782. }
  2783. viewer.addLine(p_left_min, p_left_max, std::string("left"));
  2784. viewer.addLine(p_right_min, p_right_max, std::string("right"));
  2785. while (!viewer.wasStopped()) {
  2786. viewer.spinOnce(100);
  2787. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  2788. }
  2789. }
  2790. }
  2791. float CRootStockGrabPoint::get_stem_width(
  2792. pcl::ModelCoefficients::Ptr edge_line_left,
  2793. pcl::ModelCoefficients::Ptr edge_line_right,
  2794. pcl::PointXYZ& p_left_min,
  2795. pcl::PointXYZ& p_left_max,
  2796. pcl::PointXYZ& p_right_min,
  2797. pcl::PointXYZ& p_right_max
  2798. )
  2799. {
  2800. float stem_width = 0.0;
  2801. double ymin = m_cparam.rs_grab_ymin;
  2802. double ymax = m_cparam.rs_grab_ymax;
  2803. double yup = m_cparam.rs_grab_fork_yup;
  2804. double ybt = m_cparam.rs_grab_fork_ybt;
  2805. double offset = m_cparam.rs_grab_offset_cut;
  2806. if (m_dtype == 0) {
  2807. ymin = m_cparam.sc_grab_ymin;
  2808. ymax = m_cparam.sc_grab_ymax;
  2809. yup = m_cparam.sc_grab_fork_yup;
  2810. ybt = m_cparam.sc_grab_fork_ybt;
  2811. offset = m_cparam.sc_grab_offset_cut;
  2812. }
  2813. double ycut = 0.5 * (yup + ybt) + offset;
  2814. double xleft_cut, xright_cut;
  2815. float t_left = (ymin - edge_line_left->values.at(1)) / edge_line_left->values.at(4);
  2816. double xleft = edge_line_left->values.at(3) * t_left + edge_line_left->values.at(0);
  2817. p_left_min.x = xleft;
  2818. p_left_min.y = ymin;
  2819. p_left_min.z = 0.0;
  2820. t_left = (ymax - edge_line_left->values.at(1)) / edge_line_left->values.at(4);
  2821. xleft = edge_line_left->values.at(3) * t_left + edge_line_left->values.at(0);
  2822. p_left_max.x = xleft;
  2823. p_left_max.y = ymax;
  2824. p_left_max.z = 0.0;
  2825. t_left = (ycut - edge_line_left->values.at(1)) / edge_line_left->values.at(4);
  2826. xleft_cut = edge_line_left->values.at(3) * t_left + edge_line_left->values.at(0);
  2827. float t_right = (ymin - edge_line_right->values.at(1)) / edge_line_right->values.at(4);
  2828. double xright = edge_line_right->values.at(3) * t_right + edge_line_right->values.at(0);
  2829. p_right_min.x = xright;
  2830. p_right_min.y = ymin;
  2831. p_right_min.z = 0.0;
  2832. t_right = (ymax - edge_line_right->values.at(1)) / edge_line_right->values.at(4);
  2833. xright = edge_line_right->values.at(3) * t_right + edge_line_right->values.at(0);
  2834. p_right_max.x = xright;
  2835. p_right_max.y = ymax;
  2836. p_right_max.z = 0.0;
  2837. t_right = (ycut - edge_line_right->values.at(1)) / edge_line_right->values.at(4);
  2838. xright_cut = edge_line_right->values.at(3) * t_right + edge_line_right->values.at(0);
  2839. stem_width = fabs(xleft_cut - xright_cut);
  2840. stem_width += 1.5*m_cloud_mean_dist;
  2841. return stem_width;
  2842. }
  2843. void CRootStockGrabPoint::calculate_noise(
  2844. std::vector<float>&diamters, //input
  2845. int security_radius, //input
  2846. int noise_radius, //input
  2847. std::vector<float>&noise //output
  2848. )
  2849. {
  2850. noise.clear();
  2851. float mu_noise = 0.0;
  2852. float cnt = 0.0;
  2853. int k;
  2854. for (int i = 0; i < diamters.size(); ++i) {
  2855. mu_noise = 0.0;
  2856. cnt = 0.0;
  2857. for (int di = -(security_radius + noise_radius); di <= (security_radius + noise_radius); ++di)
  2858. {
  2859. if (di >= -security_radius && di <= security_radius) { continue; }
  2860. k = i + di;
  2861. if (k < 0 || k >= diamters.size()) { continue; }
  2862. if (diamters.at(k) <= 1.0e-6) { continue; }
  2863. mu_noise += diamters.at(k);
  2864. cnt += 1.0;
  2865. }
  2866. if (cnt > 0.0) {
  2867. mu_noise /= cnt;
  2868. }
  2869. noise.push_back(mu_noise);
  2870. }
  2871. }
  2872. void CRootStockGrabPoint::get_line_project_hist(
  2873. pcl::PointCloud<pcl::PointXYZ>::Ptr in_line_cloud, //input 茎上直线点云
  2874. pcl::ModelCoefficients::Ptr line_model, //input
  2875. std::vector<int>& count_hist // 返回有效直线1mm内点云数量
  2876. )
  2877. {
  2878. count_hist.clear();
  2879. float ymin, ymax;
  2880. ymin = m_cparam.rs_grab_ymin;
  2881. ymax = m_cparam.rs_grab_ymax;
  2882. if (m_dtype == 0) {
  2883. ymin = m_cparam.sc_grab_ymin;
  2884. ymax = m_cparam.sc_grab_ymax;
  2885. }
  2886. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_inbox(new pcl::PointCloud<pcl::PointXYZ>);
  2887. pcl::CropBox<pcl::PointXYZ> box_filter_line;
  2888. box_filter_line.setNegative(false);
  2889. box_filter_line.setInputCloud(in_line_cloud);
  2890. float radius = m_cparam.rs_grab_stem_diameter;
  2891. if (m_dtype == 0) {
  2892. radius = m_cparam.sc_grab_stem_diameter;
  2893. }
  2894. float rx = 1.5;
  2895. float rz = 1.5;
  2896. float cx, cy, cz, t;
  2897. cy = ymin;
  2898. while (cy<ymax) {
  2899. t = (cy - line_model->values.at(1)) / line_model->values.at(4);
  2900. cx = line_model->values.at(3) * t + line_model->values.at(0);
  2901. cz = line_model->values.at(5) * t + line_model->values.at(2);
  2902. box_filter_line.setMin(Eigen::Vector4f(cx - rx*radius, cy - 0.5, cz - rz*radius, 1));
  2903. box_filter_line.setMax(Eigen::Vector4f(cx + rx*radius, cy + 0.5, cz + rz*radius, 1));
  2904. box_filter_line.filter(*cloud_inbox);
  2905. count_hist.push_back(cloud_inbox->points.size());
  2906. cy += 1.0;
  2907. }
  2908. }
  2909. void CRootStockGrabPoint::viewer_cloud(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, std::string&winname)
  2910. {
  2911. pcl::visualization::CloudViewer viewer(winname);
  2912. //viewer.runOnVisualizationThreadOnce(viewerOneOff);
  2913. viewer.showCloud(cloud);
  2914. while (!viewer.wasStopped()) {
  2915. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  2916. }
  2917. }
  2918. void CRootStockGrabPoint::viewer_cloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud, std::string&winname)
  2919. {
  2920. pcl::visualization::CloudViewer viewer(winname);
  2921. //viewer.runOnVisualizationThreadOnce(viewerOneOff);
  2922. viewer.showCloud(cloud);
  2923. while (!viewer.wasStopped()) {
  2924. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  2925. }
  2926. }
  2927. void CRootStockGrabPoint::viewer_cloud_debug(
  2928. pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud,
  2929. pcl::PointXYZ &p, //抓取点
  2930. pcl::PointXYZ &p_ref,//分叉点
  2931. pcl::PointXYZ &root_pt,
  2932. std::string&winname)
  2933. {
  2934. pcl::visualization::PCLVisualizer viewer(winname);
  2935. //viewer.runOnVisualizationThreadOnce(viewerOneOff);
  2936. viewer.addPointCloud(cloud);
  2937. viewer.addCoordinateSystem();
  2938. pcl::PointXYZ p0, x1, y1,p00,x0,y0, root_px0, root_px1, root_py0,root_py1;
  2939. p0.x = p.x;
  2940. p0.y = p.y;
  2941. p0.z = p.z;
  2942. x1.x = p.x + 100.0;
  2943. x1.y = p.y;
  2944. x1.z = p.z;
  2945. y1.x = p.x;
  2946. y1.y = p.y + 20.0;
  2947. y1.z = p.z;
  2948. p00.x = 0.0;
  2949. p00.y = 0.0;
  2950. p00.z = p.z;
  2951. x0.x = 600.0;
  2952. x0.y = 0;
  2953. x0.z = p.z;
  2954. y0.x = 0.0;
  2955. y0.y = 300.0;
  2956. y0.z = p.z;
  2957. root_px0.x = root_pt.x - 5.0;
  2958. root_px0.y = root_pt.y;
  2959. root_px0.z = root_pt.z;
  2960. root_px1.x = root_pt.x + 5.0;
  2961. root_px1.y = root_pt.y;
  2962. root_px1.z = root_pt.z;
  2963. root_py0.x = root_pt.x;
  2964. root_py0.y = root_pt.y;
  2965. root_py0.z = root_pt.z - 5.0;
  2966. root_py1.x = root_pt.x;
  2967. root_py1.y = root_pt.y;
  2968. root_py1.z = root_pt.z + 5.0;
  2969. //茎节点
  2970. pcl::PointXYZ fork_px0, fork_px1, fork_py0, fork_py1;
  2971. fork_px0.x = p_ref.x - 5.0;
  2972. fork_px0.y = p_ref.y;
  2973. fork_px0.z = p_ref.z;
  2974. fork_px1.x = p_ref.x + 5.0;
  2975. fork_px1.y = p_ref.y;
  2976. fork_px1.z = p_ref.z;
  2977. fork_py0.x = p_ref.x;
  2978. fork_py0.y = p_ref.y;
  2979. fork_py0.z = p_ref.z - 5.0;
  2980. fork_py1.x = p_ref.x;
  2981. fork_py1.y = p_ref.y;
  2982. fork_py1.z = p_ref.z + 5.0;
  2983. viewer.addLine(p0, x1, 255, 0, 0, "x");
  2984. viewer.addLine(p0, y1, 0, 255, 0, "y");
  2985. viewer.addLine(p00, x0, 255, 0, 0, "x0");
  2986. viewer.addLine(p00, y0, 0, 255, 0, "y0");
  2987. viewer.addLine(root_px0, root_px1, 255, 0, 0, "rootx");
  2988. viewer.addLine(root_py0, root_py1, 0, 255, 0, "rooty");
  2989. viewer.addLine(fork_px0, fork_px1, 255, 0, 0, "forkx");
  2990. viewer.addLine(fork_py0, fork_py1, 0, 255, 0, "forky");
  2991. while (!viewer.wasStopped()) {
  2992. viewer.spinOnce(100);
  2993. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  2994. }
  2995. }
  2996. void CRootStockGrabPoint::viewer_cloud_cluster(
  2997. pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud,
  2998. std::vector<pcl::PointXYZ>cluster_center,
  2999. std::string&winname)
  3000. {
  3001. pcl::visualization::PCLVisualizer viewer(winname);
  3002. viewer.addPointCloud(cloud);
  3003. viewer.addCoordinateSystem();
  3004. int cnt = 0;
  3005. char buf[8];
  3006. for (auto& p : cluster_center) {
  3007. pcl::PointXYZ px0, px1, py1, py0;
  3008. px0.x = p.x;
  3009. px0.y = p.y;
  3010. px0.z = p.z;
  3011. px1.x = p.x + 10.0;
  3012. px1.y = p.y;
  3013. px1.z = p.z;
  3014. py0.x = p.x;
  3015. py0.y = p.y;
  3016. py0.z = p.z;
  3017. py1.x = p.x;
  3018. py1.y = p.y + 10.0;
  3019. py1.z = p.z;
  3020. viewer.addLine(px0, px1, 255, 0, 0, "x" + string(_itoa(cnt, buf,10)));
  3021. viewer.addLine(py0, py1, 0, 255, 0, "y" + string(_itoa(cnt, buf, 10)));
  3022. cnt += 1;
  3023. }
  3024. while (!viewer.wasStopped()) {
  3025. viewer.spinOnce(100);
  3026. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  3027. }
  3028. }
  3029. void CRootStockGrabPoint::viewer_cloud_cluster_box(
  3030. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud,
  3031. std::vector<pcl::PointXYZ>&cluster_center,
  3032. std::vector<pcl::PointXYZ>&cluster_box,
  3033. std::vector<std::vector<int> >& clt_line_idx,
  3034. std::string&winname)
  3035. {
  3036. pcl::visualization::PCLVisualizer viewer(winname);
  3037. viewer.addCoordinateSystem();
  3038. viewer.addPointCloud<pcl::PointXYZ>(cloud, "all_cloud");
  3039. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1, 1, 1, "all_cloud");
  3040. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "all_cloud");
  3041. int cnt = 0;
  3042. char buf[8];
  3043. for (size_t i = 0; i < cluster_center.size();++i) {
  3044. pcl::PointXYZ &p = cluster_center.at(i);
  3045. pcl::PointXYZ px0, px1, py1, py0;
  3046. px0.x = p.x;
  3047. px0.y = p.y;
  3048. px0.z = p.z;
  3049. px1.x = p.x + 10.0;
  3050. px1.y = p.y;
  3051. px1.z = p.z;
  3052. py0.x = p.x;
  3053. py0.y = p.y;
  3054. py0.z = p.z;
  3055. py1.x = p.x;
  3056. py1.y = p.y + 10.0;
  3057. py1.z = p.z;
  3058. viewer.addLine(px0, px1, 255, 0, 0, "x" + string(_itoa(cnt, buf, 10)));
  3059. viewer.addLine(py0, py1, 0, 255, 0, "y" + string(_itoa(cnt, buf, 10)));
  3060. //box
  3061. pcl::PointXYZ & min_pt = cluster_box.at(2 * i);
  3062. pcl::PointXYZ & max_pt = cluster_box.at(2 * i + 1);
  3063. viewer.addCube(min_pt.x, max_pt.x, min_pt.y, max_pt.y, min_pt.z, max_pt.z, 0.5,0.5,0.0,"AABB_"+string(_itoa(cnt, buf, 10)));
  3064. viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION,
  3065. pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "AABB_" + string(_itoa(cnt, buf, 10)));
  3066. if (clt_line_idx.size()>i && clt_line_idx.at(i).size() > 0) {
  3067. pcl::PointCloud<pcl::PointXYZ>::Ptr line_cloud(new pcl::PointCloud<pcl::PointXYZ>);
  3068. pcl::copyPointCloud(*cloud, clt_line_idx.at(i), *line_cloud);
  3069. viewer.addPointCloud(line_cloud, "fit_line" + string(_itoa(cnt, buf, 10)));
  3070. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0, 1, 0, "fit_line" + string(_itoa(cnt, buf, 10)));
  3071. viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "fit_line" + string(_itoa(cnt, buf, 10)));
  3072. }
  3073. cnt += 1;
  3074. }
  3075. while (!viewer.wasStopped()) {
  3076. viewer.spinOnce(100);
  3077. boost::this_thread::sleep(boost::posix_time::microseconds(100000));
  3078. }
  3079. }
  3080. };