grab_point_rs.cpp 104 KB

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