grab_point_rs.cpp 92 KB

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