├── Cal_Linearity.m ├── ConstructEdges.m ├── FindRoots_1010.m ├── GraphOpt.m ├── GraphRG.m ├── Installer.exe ├── LICENSE ├── PathOpt.m ├── PostProssing.m ├── README.md ├── RcSeg.m ├── Seg_attributes.m ├── cover_sets.m ├── cubical_partition.m ├── main_script.m ├── segments.m ├── testdata.mat └── unique_elements.m /Cal_Linearity.m: -------------------------------------------------------------------------------- 1 | function Linearity = Cal_Linearity(Seg) 2 | % calculate linearity of each segment 3 | % input: cell array containing each segments 4 | 5 | % Di Wang, di.wang@aalto.fi 6 | %% 7 | Linearity = zeros(length(Seg),1); 8 | for i = 1:length(Seg) 9 | P = Seg{i}; 10 | [m,~] = size(P); 11 | if m>=5 12 | P = P-ones(m,1)*(sum(P,1)/m); 13 | C = P.'*P./(m-1); 14 | [~, D] = eig(C); 15 | 16 | epsilon_to_add = 1e-8; 17 | EVs = [D(3,3) D(2,2) D(1,1)]; 18 | if EVs(3) <= 0; EVs(3) = epsilon_to_add; 19 | if EVs(2) <= 0; EVs(2) = epsilon_to_add; 20 | if EVs(1) <= 0; EVs(1) = epsilon_to_add; end 21 | end 22 | end 23 | sum_EVs = EVs(1) + EVs(2) + EVs(3); 24 | % normalization of eigenvalues 25 | EVs(:,1) = EVs(:,1) ./ sum_EVs; 26 | EVs(:,2) = EVs(:,2) ./ sum_EVs; 27 | EVs(:,3) = EVs(:,3) ./ sum_EVs; 28 | 29 | Linearity(i) = ( EVs(:,1) - EVs(:,2) ) ./ EVs(:,1); 30 | end 31 | end 32 | 33 | end -------------------------------------------------------------------------------- /ConstructEdges.m: -------------------------------------------------------------------------------- 1 | function Edge = ConstructEdges(k, PtsAttri, SegAtrri) 2 | %% construct a superpoint graph 3 | % this graph is firstly constructed on points P, and then transfered to 4 | % superpoints 5 | % k: number of neighbors for knn graph 6 | % P: points 7 | % L: per point segment label 8 | % SegAtrri: segment attributes 9 | %% construct a connected knn graph for points 10 | % point wise 11 | % k = 20; 12 | P = PtsAttri.P; 13 | L = PtsAttri.L; 14 | C = SegAtrri.C; 15 | %% 16 | n_point = size(P,1); 17 | %---compute full adjacency graph------------------------------------------- 18 | [neighbors,~] = knnsearch(P,P,'K', k+1); 19 | % remove point itself 20 | neighbors = neighbors(:,2:end); 21 | % convert to nx2 matrix 22 | source = reshape(repmat(1:n_point, [k 1]), [1 (k * n_point)])'; 23 | target = reshape(neighbors', [1 (k * n_point)])'; 24 | clear neighbors distance prune2 pruned 25 | 26 | %% -----transform point wise to segment wise------------------------------ 27 | S_source = L(source); 28 | S_target = L(target); 29 | 30 | % remove those with very long horizontal distances 31 | dump = C(S_source,1:2) - C(S_target,1:2); 32 | dis = sqrt(sum(dump.^2,2)); 33 | disthres = prctile(dis,99.9); 34 | S_source(dis > disthres) = []; 35 | S_target(dis > disthres) = []; 36 | clear dump dis 37 | % remove redundant edges 38 | selfedge = S_source==S_target; 39 | S_source = S_source(~selfedge); 40 | S_target = S_target(~selfedge); 41 | 42 | Edge = [S_source,S_target]; 43 | Edge = sort(Edge,2); 44 | Edge = unique(Edge, 'rows'); 45 | % symmetric 46 | Edge2 = [Edge(:,2),Edge(:,1)]; 47 | Edge = [Edge;Edge2]; 48 | 49 | clear Edge2 source target S_source S_target selfedge 50 | 51 | end -------------------------------------------------------------------------------- /FindRoots_1010.m: -------------------------------------------------------------------------------- 1 | function SegAtrri = FindRoots_1010(SegAtrri, Gp, Lp_thres, direction_thres, S_thres, H_thres, Merge_thres) 2 | %% find root segments 3 | 4 | 5 | Updated_Pli = SegAtrri.Updated_Pli; 6 | Lp = SegAtrri.Lp; 7 | direction = SegAtrri.direction; 8 | S = SegAtrri.S; 9 | H = SegAtrri.H; 10 | Hp = SegAtrri.Hp; 11 | 12 | %% find roots 13 | % wood segs 14 | ia = find(Updated_Pli >= 0.5); 15 | % % candidate root segs 16 | ia(Lp(ia,3)>Lp_thres | abs(direction(ia,3))=Tp(3)*0.8); 68 | Pclust(ismember(Rt2(Pclust),Mg)) = []; 69 | 70 | % find nearest one 71 | nrs = Pclust(find(Hdis(Pclust) == min(Hdis(Pclust)),1)); 72 | % merge this one 73 | Mg = [Mg;Rt2(nrs)]; 74 | % update highest point 75 | Tp = Hp(Rt2(nrs),:); 76 | end 77 | Mg = unique(Mg); 78 | 79 | merge{mm} = Mg; 80 | mm = mm+1; 81 | Rt2(ismember(Rt2,Mg)) = []; 82 | end 83 | 84 | merge(cellfun(@isempty,merge)) = []; 85 | 86 | %% Final root segments 87 | Root_id = nan(length(merge),1); 88 | for i = 1:length(merge) 89 | tmp = merge{i}; 90 | if length(tmp)>1 91 | 92 | Root_id(i) = tmp(find(Lp(tmp,3) == min(Lp(tmp,3)),1)); 93 | else 94 | Root_id(i) = tmp; 95 | end 96 | end 97 | 98 | %% 99 | SegAtrri.Root_id = Root_id; 100 | end 101 | -------------------------------------------------------------------------------- /GraphOpt.m: -------------------------------------------------------------------------------- 1 | function [SegAtrri, PtsAttri] = GraphOpt(Edge, Seg_final, SegAtrri, PtsAttri) 2 | %% update segment level Pli with graph optimization 3 | % Updated_Pli: updated Pli for segments 4 | % Pboriginal: original point level pli 5 | % PbUpdate: updated point level pli 6 | 7 | %% 8 | S = SegAtrri.S; 9 | Pli = SegAtrri.Pli; 10 | 11 | 12 | [t_label,~,ic] = unique(Edge(:,1)); 13 | t = accumarray(ic,Edge(:,2),[],@(x) {x}); 14 | 15 | Initial_Pli = Pli; 16 | aa = 1; 17 | ite = 0; 18 | while aa>0.05 && ite<3 19 | 20 | Npli = nan(length(t_label),1); 21 | for i = 1:length(t_label) 22 | current_Seg = t_label(i); 23 | neighbor_Seg = t{i}; 24 | 25 | all = [current_Seg;neighbor_Seg]; 26 | Npli(i) = sum(S(all).*Pli(all))/sum(S(all)); 27 | end 28 | 29 | Updated_Pli = Pli; 30 | Updated_Pli(t_label) = Npli; 31 | 32 | aa = mean(abs(Updated_Pli - Pli)); 33 | 34 | Pli = Updated_Pli; 35 | end 36 | 37 | % upwrap segments to points, so we can operate on point level 38 | Pboriginal = cell(length(Seg_final),1); 39 | PbUpdate = cell(length(Seg_final),1); 40 | for i = 1:length(Seg_final) 41 | dump = Seg_final{i}; 42 | Pboriginal{i} = repmat(Initial_Pli(i),size(dump,1),1); 43 | PbUpdate{i} = repmat(Updated_Pli(i),size(dump,1),1); 44 | end 45 | Pboriginal = cell2mat(Pboriginal); 46 | PbUpdate = cell2mat(PbUpdate); 47 | 48 | % figure 49 | % subplot(1,2,1) 50 | % pcshow(P, Pboriginal) 51 | % axis off 52 | % subplot(1,2,2) 53 | % pcshow(P, PbUpdate) 54 | % axis off 55 | % 56 | % clear Pli ic t t_label 57 | 58 | SegAtrri.Updated_Pli = Updated_Pli; 59 | PtsAttri.Pboriginal = Pboriginal; 60 | PtsAttri.PbUpdate = PbUpdate; 61 | end -------------------------------------------------------------------------------- /GraphRG.m: -------------------------------------------------------------------------------- 1 | function Label = GraphRG(X, feature, k, ft_threshold) 2 | 3 | % graph based region growing 4 | %(clustering using graph -> connected components in graph) 5 | 6 | % X: nx3 points 7 | % feature: nx1 feature vector (z value of normal vector) 8 | % k: number of neighbors used for graph built 9 | % nz_threshold: feature threshold 10 | % output Label 1 to n defines class label of each point 11 | 12 | % Di Wang, di.wang@aalto.fi 13 | %% 14 | n_point = size(X,1); 15 | %---compute full adjacency graph------------------------------------------- 16 | [neighbors,distance] = knnsearch(X,X,'K', k+1); 17 | % remove point itself 18 | neighbors = neighbors(:,2:end); 19 | distance = distance(:,2:end); 20 | % convert to nx2 matrix 21 | source = reshape(repmat(1:n_point, [k 1]), [1 (k * n_point)])'; 22 | target = reshape(neighbors', [1 (k * n_point)])'; 23 | 24 | %% ---pruning---------------------------------------------------------------- 25 | % for each point, remove its neighbors that farther than (mean+std) 26 | dt = mean(distance,2) + 1*std(distance,0,2); 27 | prune = bsxfun(@gt,distance',dt')'; 28 | pruned = reshape(prune', [1 (k * n_point)])'; 29 | 30 | % define the farthest distance maxd, remove all neighbors farther than it 31 | maxd = mean(distance(:,end)) + 1*std(distance(:,end)); 32 | prune2 = distance > maxd; 33 | pruned2 = reshape(prune2', [1 (k * n_point)])'; 34 | 35 | %% ---remove self edges and pruned edges------------------------------------- 36 | % self edges 37 | selfedge = source==target; 38 | % all edges to be removed 39 | to_remove = selfedge + pruned + pruned2; 40 | % remove them 41 | source = source(~to_remove); 42 | target = target(~to_remove); 43 | 44 | %% test edges again feature threshold 45 | dv = nan(length(source),1); 46 | for j = 1:length(source) 47 | dv(j) = abs(abs(feature(source(j))) - abs(feature(target(j)))); 48 | end 49 | % graph edges 50 | source = source(dv<=ft_threshold,:); 51 | target = target(dv<=ft_threshold,:); 52 | 53 | %% flip edges 54 | Edge = [source,target]; 55 | Edge2 = [Edge(:,2),Edge(:,1)]; 56 | % final graph edges 57 | Edge = [Edge;Edge2]; 58 | 59 | %% construct a graph based on edge list 60 | adj = sparse(Edge(:,1),Edge(:,2),ones(size(Edge,1),1),size(X,1),size(X,1)); 61 | Gp = graph(adj); 62 | 63 | %% find connected components of the graph 64 | Label = conncomp(Gp); 65 | Label = Label'; 66 | 67 | end -------------------------------------------------------------------------------- /Installer.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwang520/SSSC/efef5aaf393b44110de91a86769fd98585d21703/Installer.exe -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /PathOpt.m: -------------------------------------------------------------------------------- 1 | function SegAtrri = PathOpt(Gp, SegAtrri) 2 | 3 | 4 | treeids = unique(SegAtrri.treeid(~isnan(SegAtrri.treeid))); 5 | 6 | visited_paths = cell(length(treeids),1); 7 | for i = 1:length(treeids) 8 | ia = find(SegAtrri.treeid == treeids(i)); 9 | Pia = SegAtrri.Updated_Pli(ia); 10 | Wia = ia(Pia>=0.8); % wood segments connected to Root_id(treeids(i)) 11 | 12 | if isempty(Wia)~=1 13 | TR = shortestpathtree(Gp,Wia,SegAtrri.Root_id(treeids(i)),'OutputForm','cell'); 14 | % redistribution 15 | path_u = cell(length(TR),1); 16 | for j = 1:length(TR) 17 | dump = TR{j}; 18 | wsn = sum(SegAtrri.Updated_Pli(dump)>=0.5); 19 | dump = flip(dump); 20 | path_u{j} = dump(1:wsn); 21 | end 22 | visited_paths{i} = cell2mat(path_u')'; 23 | end 24 | end 25 | visited_paths = cell2mat(visited_paths); 26 | 27 | tbl = tabulate(visited_paths); 28 | 29 | Seg_Visit_Freq = zeros(size(SegAtrri.C,1),1); 30 | if isempty(tbl) ~= 1 31 | Seg_Visit_Freq(tbl(:,1)) = tbl(:,2); 32 | end 33 | %% apply graph path optimization 34 | ia = find(Seg_Visit_Freq>0); 35 | ib = ia(SegAtrri.Updated_Pli(ia)<0.5); 36 | % ****** final segment level wood/leaf probability ******** 37 | Final_Pli = SegAtrri.Updated_Pli; 38 | Final_Pli(ib) = 0.51; 39 | 40 | %% 41 | SegAtrri.Final_Pli = Final_Pli; 42 | 43 | end -------------------------------------------------------------------------------- /PostProssing.m: -------------------------------------------------------------------------------- 1 | function [PtsAttri, SegAtrri] = PostProssing(Seg_final, SegAtrri, PtsAttri, lthres, dthres) 2 | % new version 3 | %% remove low vegetations 4 | 5 | ia = find(PtsAttri.P(:,3)lthres,:) = []; 8 | 9 | [~,D] = knnsearch(rootpoints(:,1:2),PtsAttri.P(ia,1:2)); 10 | 11 | % vegetation points 12 | vegep = ia(D>dthres); 13 | 14 | PtsAttri.Treeid(vegep) = 0; 15 | 16 | %% 17 | %% deal with unconnected points (to nearest valid points) 18 | ia = isnan(PtsAttri.Treeid); 19 | unlabeledP = PtsAttri.P(ia,:); 20 | restP = PtsAttri.P(~ia,:); 21 | restTid = PtsAttri.Treeid(~ia); 22 | 23 | idx = knnsearch(restP, unlabeledP); 24 | PtsAttri.Treeid(ia) = restTid(idx); 25 | 26 | %% old version 27 | % % figure 28 | % % pcshow(PtsAttri.P,PtsAttri.Treeid) 29 | % % colormap(gca,[colorcube(max(PtsAttri.Treeid))]) 30 | % % grid off 31 | % % figure 32 | % % pcshow(PtsAttri.P,double(PtsAttri.Pbfinal>=0.5)) 33 | % % colormap(gca,'parula') 34 | % % grid off 35 | % 36 | % %% deal with unconnected points (to nearest valid points) 37 | % ia = isnan(PtsAttri.Treeid); 38 | % unlabeledP = PtsAttri.P(ia,:); 39 | % restP = PtsAttri.P(~ia,:); 40 | % restTid = PtsAttri.Treeid(~ia); 41 | % 42 | % idx = knnsearch(restP, unlabeledP); 43 | % PtsAttri.Treeid(ia) = restTid(idx); 44 | % 45 | % 46 | % % ia = isnan(PtsAttri.Treeid); 47 | % % unlabeledP = PtsAttri.P(ia,:); 48 | % % 49 | % % idx = knnsearch(SegAtrri.Lp(SegAtrri.Root_id,1:2), unlabeledP(:,1:2)); 50 | % % PtsAttri.Treeid(ia) = idx; 51 | % % clear idx ia unlabeledP 52 | % 53 | % 54 | % 55 | % %% remove low vegetations 56 | % 57 | % ia = find(PtsAttri.P(:,3)lthres,:) = []; 60 | % 61 | % [~,D] = knnsearch(rootpoints(:,1:2),PtsAttri.P(ia,1:2)); 62 | % 63 | % % vegetation points 64 | % vegep = ia(D>dthres); 65 | % 66 | % PtsAttri.Treeid(vegep) = 0; 67 | % 68 | % % figure 69 | % % pcshow(PtsAttri.P,PtsAttri.Treeid) 70 | % % colormap(colorcube(max(PtsAttri.Treeid))) 71 | % % grid off 72 | 73 | end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SSSC 2 | An Unsupervised and Joint Framework for Single Tree Isolation and Leaf-wood Classification 3 | -------------------------------------------------------------------------------- /RcSeg.m: -------------------------------------------------------------------------------- 1 | function Seg_final = RcSeg(points, ft_threshold, nThreads) 2 | %% recursive segmentation 3 | 4 | 5 | 6 | %% 7 | normals = pcnormals(pointCloud(points(:,1:3)),10); 8 | % ft_threshold = 0.125; 9 | k = 10; 10 | Label = GraphRG(points, normals(:,3), k, ft_threshold); 11 | 12 | t = accumarray(Label,[1:length(Label)]',[],@(x) {x}); 13 | Seg = cellfun(@(x) points(x,:),t,'UniformOutput',0); 14 | lb = cellfun(@(x) size(x,1),Seg); 15 | 16 | Seg_reserve = Seg(lb<=10); 17 | Seg_processing = Seg(lb>10); 18 | clear Seg t lb Label normals 19 | 20 | p = gcp('nocreate'); 21 | if isempty(p) 22 | parpool('local',nThreads); 23 | end 24 | %% recursive segmentation 25 | for ii = 1:inf 26 | 27 | TMP = cell(length(Seg_processing),1); 28 | indx = false(length(Seg_processing),1); 29 | parfor i = 1:length(Seg_processing) 30 | points_n = Seg_processing{i}; 31 | normals = pcnormals(pointCloud(points_n(:,1:3)),10); 32 | Label = GraphRG(points_n, normals(:,3), k, ft_threshold); 33 | 34 | if max(Label)==1 35 | indx(i) = true; 36 | else 37 | t = accumarray(Label,[1:length(Label)]',[],@(x) {x}); 38 | Seg = cellfun(@(x) points_n(x,:),t,'UniformOutput',0); 39 | 40 | TMP{i} = Seg; 41 | end 42 | end 43 | 44 | Seg = cat(1, TMP{:}); 45 | 46 | unchange = Seg_processing(indx); 47 | 48 | if sum(indx) == length(Seg_processing) || ii == 10 % very unlikely the iteration will exceed 10 49 | Seg_final = [Seg;Seg_reserve;unchange]; 50 | break 51 | else 52 | lb = cellfun(@(x) size(x,1),Seg); 53 | 54 | Seg_processing = Seg(lb>10); 55 | 56 | Seg_reserve = [Seg_reserve;unchange;Seg(lb<=10)]; 57 | end 58 | end 59 | 60 | clear Seg_reserve unchange Seg_processing Seg 61 | %% 62 | % cmap = hsv(length(Seg_final)); 63 | % pz = randperm(size(cmap,1),size(cmap,1)); 64 | % cmap = cmap(pz,:); 65 | % col = cell(length(Seg_final),1); 66 | % for i =1:length(Seg_final) 67 | % ww = Seg_final{i}; 68 | % col(i) = {repmat(cmap(i,:),size(ww,1),1)}; 69 | % end 70 | % figure;pcshow(cell2mat(Seg_final),cell2mat(col));grid off; 71 | % clear cmap pz col 72 | %% 73 | Inputs.PatchDiam1 = 0.1; % Patch size of the first uniform-size cover 74 | Inputs.PatchDiam2Min = 0.03; % Minimum patch size of the cover sets in the second cover 75 | Inputs.PatchDiam2Max = 0.08; % Maximum cover set size in the stem's base in the second cover 76 | Inputs.lcyl = 3; % Relative (length/radius) length of the cylinders 77 | Inputs.FilRad = 3; % Relative radius for outlier point filtering 78 | Inputs.BallRad1 = Inputs.PatchDiam1+0.02; % Ball radius in the first uniform-size cover generation 79 | Inputs.BallRad2 = Inputs.PatchDiam2Max+0.01; % Maximum ball radius in the second cover generation 80 | Inputs.nmin1 = 3; % Minimum number of points in BallRad1-balls, generally good value is 3 81 | Inputs.nmin2 = 1; % Minimum number of points in BallRad2-balls, generally good value is 1 82 | Inputs.OnlyTree = 1; % If 1, point cloud contains points only from the tree 83 | 84 | %% slipt segments 85 | % addpath('./TreeQSM_src') 86 | % linearity = Cal_Linearity(Seg_final); 87 | Seg_post = cell(length(Seg_final),1); 88 | parfor i = 1:length(Seg_final) 89 | 90 | pts = Seg_final{i}; 91 | if size(pts,1)>100 && (max(pts(:,3)) - min(pts(:,3)))>1 92 | % Generate cover sets 93 | cover1 = cover_sets(pts,Inputs); 94 | if length(cover1.ball) > 2 95 | Base = find(pts(cover1.center,3) == min(pts(cover1.center,3))); 96 | Forb = false(length(cover1.center),1); 97 | segment1 = segments(cover1,Base,Forb); 98 | Seg_tmp = cell(length(segment1.segments),1); 99 | for j = 1:length(segment1.segments) 100 | ids = cell2mat(cover1.ball(cell2mat(segment1.segments{j}))); 101 | Seg_tmp{j} = pts(ids,:); 102 | end 103 | Seg_post{i} = Seg_tmp; 104 | else 105 | Seg_post{i} = {pts}; 106 | end 107 | else 108 | Seg_post{i} = {pts}; 109 | end 110 | end 111 | Seg_final= cat(1, Seg_post{:}); 112 | clear Seg_post 113 | 114 | 115 | end -------------------------------------------------------------------------------- /Seg_attributes.m: -------------------------------------------------------------------------------- 1 | function [PtsAttri, SegAtrri] = Seg_attributes(Seg_final) 2 | %% calculate segments attributes 3 | % SegAtrri.C: segment center point - superpoints 4 | % SegAtrri.S: segment size 5 | % SegAtrri.Lp: segment lowest point 6 | % SegAtrri.Hp: segment highest point 7 | % SegAtrri.: segment length 8 | % SegAtrri.direction:segment orientation 9 | % SegAtrri.Pli: segment wood probability 10 | %% also export point attributes 11 | % PtsAttri.P: unwrapped points 12 | % PtsAttri.L: per point segment label 13 | %% ------------------------------ 14 | % calculate linearity of each segment 15 | linearity = Cal_Linearity(Seg_final); 16 | % calculate size of each segment 17 | sl = cellfun(@(x)size(x,1),Seg_final); 18 | 19 | % test a range of thresholds 20 | Lthres_list = 0.70:0.02:0.95; 21 | Sthres_list = 10:2:50; 22 | % all combinations of two thresholds 23 | allc = combvec(Lthres_list,Sthres_list)'; 24 | % 25 | Freq = zeros(length(Seg_final),1); 26 | for i = 1:size(allc,1) 27 | % find wood segments based on two thresholds 28 | ia = linearity >= allc(i,1) & sl >= allc(i,2); 29 | % count the frequency of being identified as wood 30 | Freq = Freq + ia; 31 | end 32 | 33 | % Probability that a segment is wood !!! 34 | Pli = Freq/size(allc,1); 35 | 36 | clear linearity sl Lthres_list Sthres_list allc Freq ia 37 | %% segment features 38 | C = nan(size(Seg_final,1),3); % segment center point - superpoints 39 | L = cell(size(Seg_final,1),1);% point segment label 40 | S = nan(size(Seg_final,1),1); % segment size 41 | Lp = nan(size(Seg_final,1),3); % segment lowest point 42 | Hp = nan(size(Seg_final,1),3); % segment highest point 43 | H = nan(size(Seg_final,1),1); % segment length 44 | direction = zeros(length(Seg_final),3); %segment orientation 45 | parfor i = 1:size(Seg_final,1) 46 | dump = Seg_final{i}; 47 | ia = size(dump,1); 48 | S(i) = ia; 49 | H(i) = max(dump(:,3)) - min(dump(:,3)); 50 | L{i} = i*ones(ia,1); 51 | 52 | dis = sqrt(sum((dump - mean(dump,1)).^2,2)); 53 | C(i,:) = dump(find(dis == min(dis),1),:); 54 | 55 | Lp(i,:) = dump(find(dump(:,3) == min(dump(:,3)),1),:); 56 | Hp(i,:) = dump(find(dump(:,3) == max(dump(:,3)),1),:); 57 | 58 | if size(dump,1)>3 59 | coeff = pca(dump); 60 | direction(i,:) = coeff(:, 1); 61 | end 62 | end 63 | 64 | L = cell2mat(L); 65 | P = cell2mat(Seg_final); % point cloud 66 | 67 | % poolobj = gcp('nocreate'); 68 | % delete(poolobj); 69 | 70 | %% write to a structure 71 | SegAtrri.C = C; 72 | SegAtrri.S = S; 73 | SegAtrri.Lp = Lp; 74 | SegAtrri.H = H; 75 | SegAtrri.Hp = Hp; 76 | SegAtrri.direction = direction; 77 | SegAtrri.Pli = Pli; 78 | 79 | PtsAttri.P = P; 80 | PtsAttri.L = L; 81 | end -------------------------------------------------------------------------------- /cover_sets.m: -------------------------------------------------------------------------------- 1 | % This file is part of TREEQSM. 2 | % 3 | % TREEQSM is free software: you can redistribute it and/or modify 4 | % it under the terms of the GNU General Public License as published by 5 | % the Free Software Foundation, either version 3 of the License, or 6 | % (at your option) any later version. 7 | % 8 | % TREEQSM is distributed in the hope that it will be useful, 9 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | % GNU General Public License for more details. 12 | % 13 | % You should have received a copy of the GNU General Public License 14 | % along with TREEQSM. If not, see . 15 | 16 | function cover = cover_sets(P,inputs,RelSize) 17 | 18 | % --------------------------------------------------------------------- 19 | % COVER_SETS.M Creates cover sets (surface patches) and their 20 | % neighbor-relation for a point cloud 21 | % 22 | % Version 2.00 23 | % Latest update 16 Aug 2017 24 | % 25 | % Copyright (C) 2013-2017 Pasi Raumonen 26 | % --------------------------------------------------------------------- 27 | 28 | % Covers the point cloud with small sets, which are along the surface, 29 | % such that each point belongs at most one cover set; i.e. the cover is 30 | % a partition of the point cloud. 31 | % 32 | % The cover is generated such that at first the point cloud is covered 33 | % with balls with radius "BallRad". This first cover is such that 34 | % 1) the minimum distance between the centers is "PatchDiam", and 35 | % 2) the maximum distance from any point to nearest center is also "PatchDiam". 36 | % Then the first cover of BallRad-balls is used to define a second cover: 37 | % each BallRad-ball "A" defines corresponding cover set "B" in the second cover 38 | % such that "B" contains those points of "A" that are nearer to the center of 39 | % "A" than any other center of BallRad-balls. The BallRad-balls also define 40 | % the neighbors for the second cover: Let CA and CB denote cover sets in 41 | % the second cover, and BA and BB their BallRad-balls. Then CB is 42 | % a neighbor of CA, and vice versa, if BA and CB intersect or 43 | % BB and CA intersect. 44 | % 45 | % Inputs: 46 | % P Point cloud 47 | % inputs Input stucture, the following fields are needed: 48 | % PatchDiam Minimum distance between centers of cover sets; i.e. the 49 | % minimum diameter of a cover set. If "RelSize" is given 50 | % as input, then there is minimum and maximum PatchDiam 51 | % BallRad Radius of the balls used to generate the cover sets, these 52 | % balls are also used to determine the neighbors and the 53 | % cover set characteristics 54 | % nmin Minimum number of points in a rcov-ball 55 | % RelSize Relative cover set size for each point 56 | % 57 | % Outputs: 58 | % cover Structure array containing the followin fields: 59 | % ball Cover sets, (n_sets x 1)-cell 60 | % center Center points of the cover sets, (n_sets x 1)-vector 61 | % neighbor Neighboring cover sets of each cover set, (n_sets x 1)-cell 62 | 63 | if ~isa(P,'double') 64 | P = double(P); 65 | end 66 | 67 | %% Large balls and centers 68 | np = size(P,1); 69 | Ball = cell(np,1); % the large balls, used to generate the cover sets and their neighbors 70 | Cen = zeros(np,1,'uint32'); % the center points of the balls/cover sets 71 | NotExa = true(np,1); % the points not yet examined 72 | Dist = 1e8*ones(np,1,'single'); % distance of point to the closest center 73 | BoP = zeros(np,1,'uint32'); % the balls/cover sets the points belong 74 | nb = 0; % number of sets generated 75 | if nargin == 2 76 | %% Same size cover sets everywhere 77 | BallRad = inputs.BallRad1; 78 | PatchDiamMax = inputs.PatchDiam1; 79 | nmin = inputs.nmin1; 80 | % Partition the point cloud into cubes for quick neighbor search 81 | [partition,CC] = cubical_partition(P,BallRad); 82 | 83 | % Generate the balls 84 | Radius = BallRad^2; 85 | MaxDist = PatchDiamMax^2; 86 | RandPerm = uint32(randperm(np)); % random permutation of points, 87 | % results in different covers for same input 88 | for i = 1:np 89 | if NotExa(RandPerm(i)) 90 | Q = RandPerm(i); 91 | points = partition(CC(Q,1)-1:CC(Q,1)+1,CC(Q,2)-1:CC(Q,2)+1,CC(Q,3)-1:CC(Q,3)+1); 92 | points = vertcat(points{:}); 93 | V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)]; 94 | dist = sum(V.*V,2); 95 | J = dist < Radius; 96 | if nnz(J) >= nmin 97 | I = points(J); 98 | d = dist(J); 99 | J = (dist < MaxDist); 100 | NotExa(points(J)) = false; 101 | nb = nb+1; 102 | Ball{nb} = I; 103 | Cen(nb) = Q; 104 | D = Dist(I); 105 | L = d < D; 106 | I = I(L); 107 | Dist(I) = d(L); 108 | BoP(I) = nb; 109 | end 110 | end 111 | end 112 | Ball = Ball(1:nb,:); 113 | Cen = Cen(1:nb); 114 | else 115 | %% Use relative sizes (the size varies) 116 | % Partition the point cloud into cubes 117 | BallRad = inputs.BallRad2; 118 | PatchDiamMin = inputs.PatchDiam2Min; 119 | PatchDiamMax = inputs.PatchDiam2Max; 120 | nmin = inputs.nmin2; 121 | MRS = PatchDiamMin/PatchDiamMax; 122 | r = double(1.5*(double(min(RelSize))/256*(1-MRS)+MRS)*BallRad+1e-5); % minimum radius 123 | NE = 1+ceil(BallRad/r); 124 | if NE > 4 125 | r = PatchDiamMax/4; 126 | NE = 1+ceil(BallRad/r); 127 | end 128 | [Partition,CC,~,Cubes] = cubical_partition(P,r,NE); 129 | 130 | I = RelSize == 0; % Don't use points with no size determined 131 | NotExa(I) = false; 132 | 133 | % Define random permutation of points (results in different covers for same input) 134 | % so that first small sets are generated 135 | RandPerm = zeros(np,1,'uint32'); 136 | I = RelSize <= 32; 137 | ind = uint32(1:1:np)'; 138 | I = ind(I); 139 | t1 = length(I); 140 | RandPerm(1:1:t1) = I(randperm(t1)); 141 | I = RelSize <= 128 & RelSize > 32; 142 | I = ind(I); 143 | t2 = length(I); 144 | RandPerm(t1+1:1:t1+t2) = I(randperm(t2)); 145 | t2 = t2+t1; 146 | I = RelSize > 128; 147 | I = ind(I); 148 | t3 = length(I); 149 | RandPerm(t2+1:1:t2+t3) = I(randperm(t3)); 150 | clearvars ind I 151 | %RandPerm = uint32(randperm(np)); % random permutation of points 152 | 153 | Point = zeros(round(np/1000),1,'uint32'); 154 | e = BallRad-PatchDiamMax; 155 | for i = 1:np 156 | if NotExa(RandPerm(i)) 157 | Q = RandPerm(i); 158 | rs = double(RelSize(Q))/256*(1-MRS)+MRS; % relative radius 159 | Dmin = PatchDiamMax*rs; 160 | Radius = Dmin+sqrt(rs)*e; 161 | N = ceil(Radius/r); % = number of cells needed to include the ball 162 | cubes = Cubes(CC(Q,1)-N:CC(Q,1)+N,CC(Q,2)-N:CC(Q,2)+N,CC(Q,3)-N:CC(Q,3)+N); 163 | I = cubes > 0; 164 | cubes = cubes(I); 165 | Par = Partition(cubes); 166 | S = cellfun('length',Par); 167 | stop = cumsum(S); 168 | start = [0; stop]+1; 169 | for k = 1:length(stop) 170 | Point(start(k):stop(k)) = Par{k}; 171 | end 172 | points = Point(1:stop(k)); 173 | V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)]; 174 | dist = sum(V.*V,2); 175 | J = dist < Radius^2; 176 | if nnz(J) >= nmin 177 | I = points(J); 178 | d = dist(J); 179 | J = (dist < Dmin^2); 180 | NotExa(points(J)) = false; 181 | nb = nb+1; 182 | Ball{nb} = I; 183 | Cen(nb) = Q; 184 | D = Dist(I); 185 | L = d < D; 186 | I = I(L); 187 | Dist(I) = d(L); 188 | BoP(I) = nb; 189 | end 190 | end 191 | end 192 | Ball = Ball(1:nb,:); 193 | Cen = Cen(1:nb); 194 | end 195 | clearvars RandPerm NotExa Dist 196 | 197 | %% Cover sets 198 | % Number of points in each ball and index of each point in its ball 199 | Num = zeros(nb,1,'uint32'); 200 | Ind = zeros(np,1,'uint32'); 201 | for i = 1:np 202 | if BoP(i) > 0 203 | Num(BoP(i)) = Num(BoP(i))+1; 204 | Ind(i) = Num(BoP(i)); 205 | end 206 | end 207 | 208 | % Initialization of the "Bal" 209 | Bal = cell(nb,1); 210 | for i = 1:nb 211 | Bal{i} = zeros(Num(i),1,'uint32'); 212 | end 213 | 214 | % Define the "Bal" 215 | for i = 1:np 216 | if BoP(i) > 0 217 | Bal{BoP(i),1}(Ind(i)) = i; 218 | end 219 | end 220 | 221 | %% Neighbors 222 | % Define neighbors. Sets A and B are neighbors if the large ball of A 223 | % contains points of B. Notice that this is not a symmetric relation. 224 | Nei = cell(nb,1); 225 | Fal = false(nb,1); 226 | for i = 1:nb 227 | B = Ball{i}; % the points in the big ball of cover set "i" 228 | I = (BoP(B) ~= i); 229 | N = B(I); % the points of B not in the cover set "i" 230 | N = BoP(N); 231 | 232 | % select the unique elements of N: 233 | n = length(N); 234 | if n > 2 235 | Include = true(n,1); 236 | for j = 1:n 237 | if ~Fal(N(j)) 238 | Fal(N(j)) = true; 239 | else 240 | Include(j) = false; 241 | end 242 | end 243 | Fal(N) = false; 244 | N = N(Include); 245 | elseif n == 2 246 | if N(1) == N(2) 247 | N = N(1); 248 | end 249 | end 250 | 251 | Nei{i} = uint32(N); 252 | end 253 | 254 | % Make the relation symmetric by adding, if needed, A as B's neighbor 255 | % in the case B is A's neighbor 256 | for i = 1:nb 257 | N = Nei{i}; 258 | for j = 1:length(N) 259 | K = (Nei{N(j)} == i); 260 | if ~any(K) 261 | Nei{N(j)} = uint32([Nei{N(j)}; i]); 262 | end 263 | end 264 | end 265 | 266 | % Define output 267 | clear cover 268 | cover.ball = Bal; 269 | cover.center = Cen; 270 | cover.neighbor = Nei; 271 | 272 | %% Display statistics 273 | %disp([' ',num2str(nb),' cover sets, points not covered: ',num2str(np-nnz(BoP))]) -------------------------------------------------------------------------------- /cubical_partition.m: -------------------------------------------------------------------------------- 1 | % This file is part of TREEQSM. 2 | % 3 | % TREEQSM is free software: you can redistribute it and/or modify 4 | % it under the terms of the GNU General Public License as published by 5 | % the Free Software Foundation, either version 3 of the License, or 6 | % (at your option) any later version. 7 | % 8 | % TREEQSM is distributed in the hope that it will be useful, 9 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | % GNU General Public License for more details. 12 | % 13 | % You should have received a copy of the GNU General Public License 14 | % along with TREEQSM. If not, see . 15 | 16 | function [Partition,CubeCoord,Info,Cubes] = cubical_partition(P,EL,NE) 17 | 18 | % Partitions the input point cloud into cubes. 19 | % 20 | % Inputs: 21 | % P Point cloud, (n_points x 3)-matrix 22 | % EL Length of the cube edges 23 | % NE Number of empty edge layers 24 | % 25 | % Outputs: 26 | % Partition Point cloud partitioned into cubical cells, 27 | % (nx x ny x nz)-cell, where nx,ny,nz are the number 28 | % of cubes in x,y,z-directions, respectively 29 | % CC (n_points x 3)-matrix whose rows are the cube coordinates 30 | % of each point: x,y,z-coordinates 31 | % Info The minimum coordinate values and number of cubes in each 32 | % coordinate direction 33 | 34 | if nargin == 2 35 | NE = 3; 36 | end 37 | 38 | % The vertices of the big cube containing P 39 | Min = double(min(P)); 40 | Max = double(max(P)); 41 | 42 | % Number of cubes with edge length "EdgeLength" in the sides 43 | % of the big cube 44 | N = double(ceil((Max-Min)/EL)+2*NE+1); 45 | while 8*N(1)*N(2)*N(3) > 4e9 46 | EL = 1.1*EL; 47 | N = double(ceil((Max-Min)/EL)+2*NE+1); 48 | end 49 | Info = [Min N EL NE]; 50 | 51 | % Calculates the cube-coordinates of the points 52 | CubeCoord = floor([P(:,1)-Min(1) P(:,2)-Min(2) P(:,3)-Min(3)]/EL)+NE+1; 53 | 54 | % Sorts the points according a lexicographical order 55 | LexOrd = [CubeCoord(:,1) CubeCoord(:,2)-1 CubeCoord(:,3)-1]*[1 N(1) N(1)*N(2)]'; 56 | CubeCoord = uint16(CubeCoord); 57 | [LexOrd,SortOrd] = sort(LexOrd); 58 | SortOrd = uint32(SortOrd); 59 | LexOrd = uint32(LexOrd); 60 | 61 | if nargout <= 3 62 | % Define "Partition" 63 | Partition = cell(N(1),N(2),N(3)); 64 | np = size(P,1); % number of points 65 | p = 1; % The index of the point under comparison 66 | while p <= np 67 | t = 1; 68 | while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) 69 | t = t+1; 70 | end 71 | q = SortOrd(p); 72 | Partition{CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)} = SortOrd(p:p+t-1); 73 | p = p+t; 74 | end 75 | 76 | else 77 | nc = size(unique(LexOrd),1); 78 | 79 | % Define "Partition" 80 | Cubes = zeros(N(1),N(2),N(3),'uint32'); 81 | Partition = cell(nc,1); 82 | np = size(P,1); % number of points 83 | p = 1; % The index of the point under comparison 84 | c = 0; 85 | while p <= np 86 | t = 1; 87 | while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) 88 | t = t+1; 89 | end 90 | q = SortOrd(p); 91 | c = c+1; 92 | Partition{c,1} = SortOrd(p:p+t-1); 93 | Cubes(CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)) = c; 94 | p = p+t; 95 | end 96 | end -------------------------------------------------------------------------------- /main_script.m: -------------------------------------------------------------------------------- 1 | 2 | %% recursive segmentation 3 | ft_threshold = 0.125; 4 | nThreads = 10; 5 | 6 | Seg_final = RcSeg(points, ft_threshold, nThreads); 7 | 8 | %% visualize segmentation 9 | cmap = hsv(length(Seg_final)); 10 | pz = randperm(size(cmap,1),size(cmap,1)); 11 | cmap = cmap(pz,:); 12 | col = cell(length(Seg_final),1); 13 | for i =1:length(Seg_final) 14 | ww = Seg_final{i}; 15 | col(i) = {repmat(cmap(i,:),size(ww,1),1)}; 16 | end 17 | figure;pcshow(cell2mat(Seg_final),cell2mat(col));grid off; 18 | clear cmap pz col 19 | 20 | %% calculate segment attribtues 21 | [PtsAttri, SegAtrri] = Seg_attributes(Seg_final); 22 | 23 | poolobj = gcp('nocreate'); 24 | delete(poolobj); 25 | %% construct edges for supergraph 26 | Edge = ConstructEdges(20, PtsAttri, SegAtrri); 27 | 28 | %% construct a weighted graph 29 | weight1 = sqrt(sum((SegAtrri.Lp(Edge(:,1),:) - SegAtrri.Lp(Edge(:,2),:)).^2,2)); 30 | % construct a graph based on edge list 31 | adj = sparse(Edge(:,1),Edge(:,2),weight1,length(Seg_final),length(Seg_final)); 32 | Gp = graph(adj); 33 | clear adj weight1 weight2 weight 34 | 35 | %% updae segment Pli with local graph optimization 36 | [SegAtrri, PtsAttri] = GraphOpt(Edge, Seg_final, SegAtrri, PtsAttri); 37 | clear Edge 38 | 39 | %% find roots 40 | SegAtrri = FindRoots_1010(SegAtrri, Gp, 1, 0.8, 100, 1, 0.5); 41 | 42 | % visual inspection 43 | Roots = Seg_final(SegAtrri.Root_id); 44 | cmap = hsv(length(Roots)); 45 | pz = randperm(size(cmap,1),size(cmap,1)); 46 | cmap = cmap(pz,:); 47 | col = cell(length(Roots),1); 48 | for i =1:length(Roots) 49 | ww = Roots{i}; 50 | col(i) = {repmat(cmap(i,:),size(ww,1),1)}; 51 | end 52 | figure;pcshow(cell2mat(Roots),cell2mat(col));grid off; 53 | clear cmap pz col 54 | 55 | ia = SegAtrri.Lp(:,3) <= 5; 56 | dump = cell2mat(Seg_final(ia)); 57 | dump(ismember(dump,cell2mat(Roots),'rows'),:) = []; 58 | 59 | hold on 60 | pcshow(dump,[.3 .3 .3]) 61 | hold off 62 | 63 | %% apply shortest path 64 | DBH = ones(length(SegAtrri.Root_id),1); 65 | % shortest path to each root 66 | d = distances(Gp,SegAtrri.Root_id,'Method','positive'); 67 | % weight by DBH 68 | w = DBH.^(2/3)'; 69 | d = d'./w; 70 | d(d == inf) = nan; 71 | [dump,SegAtrri.treeid] = min(d,[],2,'omitnan'); 72 | % [dump,SegAtrri.treeid] = min(d,[],2); 73 | SegAtrri.treeid(isnan(dump)) = nan; 74 | 75 | clear d 76 | 77 | figure 78 | pcshow(SegAtrri.C,SegAtrri.treeid) 79 | colormap(colorcube(max(SegAtrri.treeid))) 80 | 81 | %% Path optimization 82 | SegAtrri = PathOpt(Gp, SegAtrri); 83 | 84 | %% segment level tree id to point wise 85 | Tid = cell(size(Seg_final,1),1);% point tree id 86 | Wood = cell(size(Seg_final,1),1);% point wood/leaf 87 | for i = 1:size(Seg_final,1) 88 | dump = Seg_final{i}; 89 | Tid{i} = SegAtrri.treeid(i)*ones(size(dump,1),1); 90 | Wood{i} = SegAtrri.Final_Pli(i)*ones(size(dump,1),1); 91 | end 92 | PtsAttri.Treeid = cell2mat(Tid); 93 | PtsAttri.Pbfinal = cell2mat(Wood); 94 | clear Tid Wood dump 95 | %% post processing 96 | [PtsAttri, ~] = PostProssing(Seg_final, SegAtrri, PtsAttri, 0.13, 0.1); 97 | 98 | 99 | %% results 100 | 101 | results = [PtsAttri.P, PtsAttri.Treeid, double(PtsAttri.Pbfinal>=0.5)]; 102 | 103 | %% 104 | figure 105 | subplot(1,2,1) 106 | pcshow(PtsAttri.P, PtsAttri.Treeid) 107 | colormap(lines(max(PtsAttri.P))) 108 | title('Tree Isolation','Color', 'k','FontWeight','Normal') 109 | set(gcf,'color','w'); 110 | set(gca,'color','w'); 111 | set(gca, 'XColor', [0.15 0.15 0.15], 'YColor', [0.15 0.15 0.15], 'ZColor', [0.15 0.15 0.15]) 112 | axis off 113 | 114 | subplot(1,2,2) 115 | tmp = PtsAttri.Pbfinal>=0.5; 116 | wood = PtsAttri.P(tmp,:); 117 | leaf = PtsAttri.P(~tmp,:); 118 | 119 | pcshow(wood, repmat([0.4471, 0.3216, 0.1647],size(wood,1),1),'markersize',1); 120 | hold on 121 | pcshow(leaf, repmat([0.2667, 0.5686, 0.1961],size(leaf,1),1),'markersize',1); 122 | hold off 123 | title('Leaf-wood Separation','Color', 'k','FontWeight','Normal') 124 | set(gcf,'color','w'); 125 | set(gca,'color','w'); 126 | set(gca, 'XColor', [0.15 0.15 0.15], 'YColor', [0.15 0.15 0.15], 'ZColor', [0.15 0.15 0.15]) 127 | axis off -------------------------------------------------------------------------------- /segments.m: -------------------------------------------------------------------------------- 1 | % This file is part of TREEQSM. 2 | % 3 | % TREEQSM is free software: you can redistribute it and/or modify 4 | % it under the terms of the GNU General Public License as published by 5 | % the Free Software Foundation, either version 3 of the License, or 6 | % (at your option) any later version. 7 | % 8 | % TREEQSM is distributed in the hope that it will be useful, 9 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | % GNU General Public License for more details. 12 | % 13 | % You should have received a copy of the GNU General Public License 14 | % along with TREEQSM. If not, see . 15 | 16 | function segment = segments(cover,Base,Forb) 17 | 18 | % --------------------------------------------------------------------- 19 | % SEGMENTS.M Segments the covered point cloud into branches. 20 | % 21 | % Version 2.10 22 | % Latest update 16 Aug 2017 23 | % 24 | % Copyright (C) 2013-2017 Pasi Raumonen 25 | % --------------------------------------------------------------------- 26 | 27 | % Segments the tree into branches and records their parent-child-relations. 28 | % Bifurcations are recognized by studying connectivity of a "study" 29 | % region moving along the tree. In case of multiple connected components 30 | % in "study", the components are classified as the continuation and branches. 31 | % 32 | % Inputs: 33 | % cover Cover sets 34 | % Base Base of the tree 35 | % Forb Cover sets not part of the tree 36 | % 37 | % Outputs: 38 | % segment Structure array containing the followin fields: 39 | % segments Segments found, (n_seg x 1)-cell, each cell contains a cell array the cover sets 40 | % ParentSegment Parent segment of each segment, (n_seg x 1)-vector, 41 | % equals to zero if no parent segment 42 | % ChildSegment Children segments of each segment, (n_seg x 1)-cell 43 | 44 | Nei = cover.neighbor; 45 | nb = size(Nei,1); % The number of cover sets 46 | a = max([200000 nb/100]); % Estimate for maximum number of segments 47 | SBas = cell(a,1); % The segment bases found 48 | Segs = cell(a,1); % The segments found 49 | SPar = zeros(a,2,'uint32'); % The parent segment of each segment 50 | SChi = cell(a,1); % The children segments of each segment 51 | 52 | % Initialize SChi 53 | SChi{1} = zeros(5000,1,'uint32'); 54 | C = zeros(200,1); 55 | for i = 2:a 56 | SChi{i} = C; 57 | end 58 | NChi = zeros(a,1); % Number of child segments found for each segment 59 | 60 | Fal = false(nb,1); % Logical false-vector for cover sets 61 | s = 1; % The index of the segment under expansion 62 | b = s; % The index of the latest found base 63 | 64 | SBas{s} = Base; 65 | Seg = cell(1000,1); % The cover set layers in the current segment 66 | Seg{1} = Base; 67 | 68 | ForbAll = Fal; % The forbidden sets 69 | ForbAll(Forb) = true; 70 | ForbAll(Base) = true; 71 | Forb = ForbAll; % The forbidden sets for the segment under expansion 72 | 73 | Continue = true; % True as long as the component can be segmented further 74 | NewSeg = true; % True if the first Cut for the current segment 75 | nl = 1; % The number of cover set layers currently in the segment 76 | 77 | % Segmenting stops when there are no more segments to be found 78 | while Continue && (b < nb) 79 | 80 | % Update the forbidden sets 81 | Forb(Seg{nl}) = true; 82 | 83 | % Define the study 84 | Cut = define_cut(Nei,Seg{nl},Forb,Fal); 85 | CutSize = length(Cut); 86 | 87 | if NewSeg 88 | NewSeg = false; 89 | ns = min(CutSize,6); 90 | end 91 | 92 | % Define the components of cut and study regions 93 | if CutSize > 0 94 | CutComps = cut_components(Nei,Cut,CutSize,Fal,Fal); 95 | nc = size(CutComps,1); 96 | if nc > 1 97 | [StudyComps,Bases,CompSize,Cont,BaseSize] = ... 98 | study_components(Nei,ns,Cut,CutComps,Forb,Fal,Fal); 99 | nc = length(Cont); 100 | end 101 | else 102 | nc = 0; 103 | end 104 | 105 | % Classify study region components 106 | if nc == 1 107 | % One component, continue expansion of the current segment 108 | nl = nl+1; 109 | if size(Cut,2) > 1 110 | Seg{nl} = Cut'; 111 | else 112 | Seg{nl} = Cut; 113 | end 114 | elseif nc > 1 115 | % Classify the components of the Study region 116 | Class = component_classification(CompSize,Cont,BaseSize,CutSize); 117 | 118 | for i = 1:nc 119 | if Class(i) == 1 120 | Base = Bases{i}; 121 | ForbAll(Base) = true; 122 | Forb(StudyComps{i}) = true; 123 | J = Forb(Cut); 124 | Cut = Cut(~J); 125 | b = b+1; 126 | SBas{b} = Base; 127 | SPar(b,:) = [s nl]; 128 | NChi(s) = NChi(s)+1; 129 | SChi{s}(NChi(s)) = b; 130 | end 131 | end 132 | 133 | % Define the new cut. 134 | % If the cut is empty, determine the new base 135 | if isempty(Cut) 136 | Segs{s} = Seg(1:nl); 137 | S = vertcat(Seg{1:nl}); 138 | ForbAll(S) = true; 139 | 140 | if s < b 141 | s = s+1; 142 | Seg{1} = SBas{s}; 143 | Forb = ForbAll; 144 | NewSeg = true; 145 | nl = 1; 146 | else 147 | Continue = false; 148 | end 149 | else 150 | if size(Cut,2) > 1 151 | Cut = Cut'; 152 | end 153 | nl = nl+1; 154 | Seg{nl} = Cut; 155 | end 156 | 157 | else 158 | % If the study region has zero size, then the current segment is 159 | % complete and determine the base of the next segment 160 | Segs{s} = Seg(1:nl); 161 | S = vertcat(Seg{1:nl}); 162 | ForbAll(S) = true; 163 | 164 | if s < b 165 | s = s+1; 166 | Seg{1} = SBas{s}; 167 | Forb = ForbAll; 168 | NewSeg = true; 169 | nl = 1; 170 | else 171 | Continue = false; 172 | end 173 | end 174 | end 175 | Segs = Segs(1:b); 176 | SPar = SPar(1:b,:); 177 | schi = SChi(1:b); 178 | 179 | % Define output 180 | SChi = cell(b,1); 181 | for i = 1:b 182 | if NChi(i) > 0 183 | SChi{i} = uint32(schi{i}(1:NChi(i))); 184 | else 185 | SChi{i} = zeros(0,1,'uint32'); 186 | end 187 | S = Segs{i}; 188 | for j = 1:size(S,1) 189 | S{j} = uint32(S{j}); 190 | end 191 | Segs{i} = S; 192 | end 193 | clear Segment 194 | segment.segments = Segs; 195 | segment.ParentSegment = SPar; 196 | segment.ChildSegment = SChi; 197 | 198 | end % End of the main function 199 | 200 | 201 | % Define subfunctions 202 | 203 | function Cut = define_cut(Nei,CutPre,Forb,Fal) 204 | 205 | % Defines the "Cut" region 206 | Cut = vertcat(Nei{CutPre}); 207 | Cut = unique_elements(Cut,Fal); 208 | I = Forb(Cut); 209 | Cut = Cut(~I); 210 | end % End of function 211 | 212 | 213 | function [Components,CompSize] = cut_components(Nei,Cut,CutSize,Fal,False) 214 | 215 | % Define the connected components of the Cut 216 | if CutSize == 1 217 | % Cut is connected and therefore Study is also 218 | CompSize = 1; 219 | Components = cell(1,1); 220 | Components{1} = Cut; 221 | elseif CutSize == 2 222 | I = Nei{Cut(1)} == Cut(2); 223 | if any(I) 224 | Components = cell(1,1); 225 | Components{1} = Cut; 226 | CompSize = 1; 227 | else 228 | Components = cell(2,1); 229 | Components{1} = Cut(1); 230 | Components{2} = Cut(2); 231 | CompSize = [1 1]; 232 | end 233 | elseif CutSize == 3 234 | I = Nei{Cut(1)} == Cut(2); 235 | J = Nei{Cut(1)} == Cut(3); 236 | K = Nei{Cut(2)} == Cut(3); 237 | if any(I)+any(J)+any(K) >= 2 238 | CompSize = 1; 239 | Components = cell(1,1); 240 | Components{1} = Cut; 241 | elseif any(I) 242 | Components = cell(2,1); 243 | Components{1} = Cut(1:2); 244 | Components{2} = Cut(3); 245 | CompSize = [2 1]; 246 | elseif any(J) 247 | Components = cell(2,1); 248 | Components{1} = Cut([1 3]'); 249 | Components{2} = Cut(2); 250 | CompSize = [2 1]; 251 | elseif any(K) 252 | Components = cell(2,1); 253 | Components{1} = Cut(2:3); 254 | Components{2} = Cut(1); 255 | CompSize = [2 1]; 256 | else 257 | CompSize = [1 1 1]; 258 | Components = cell(3,1); 259 | Components{1} = Cut(1); 260 | Components{2} = Cut(2); 261 | Components{3} = Cut(3); 262 | end 263 | else 264 | Components = cell(CutSize,1); 265 | CompSize = zeros(CutSize,1); 266 | Comp = zeros(CutSize,1); 267 | Fal(Cut) = true; 268 | nc = 0; % number of components found 269 | m = Cut(1); 270 | i = 0; 271 | while i < CutSize 272 | Added = Nei{m}; 273 | I = Fal(Added); 274 | Added = Added(I); 275 | a = length(Added); 276 | Comp(1) = m; 277 | Fal(m) = false; 278 | t = 1; 279 | while a > 0 280 | Comp(t+1:t+a) = Added; 281 | Fal(Added) = false; 282 | t = t+a; 283 | Ext = vertcat(Nei{Added}); 284 | Ext = unique_elements(Ext,False); 285 | I = Fal(Ext); 286 | Added = Ext(I); 287 | a = length(Added); 288 | end 289 | i = i+t; 290 | nc = nc+1; 291 | Components{nc} = Comp(1:t); 292 | CompSize(nc) = t; 293 | if i < CutSize 294 | J = Fal(Cut); 295 | m = Cut(J); 296 | m = m(1); 297 | end 298 | end 299 | Components = Components(1:nc); 300 | CompSize = CompSize(1:nc); 301 | end 302 | 303 | end % End of function 304 | 305 | 306 | function [Components,Bases,CompSize,Cont,BaseSize] = ... 307 | study_components(Nei,ns,Cut,CutComps,Forb,Fal,False) 308 | 309 | % Define Study as a cell-array 310 | Study = cell(ns,1); 311 | StudySize = zeros(ns,1); 312 | Study{1} = Cut; 313 | StudySize(1) = length(Cut); 314 | if ns >= 2 315 | N = Cut; 316 | i = 1; 317 | while i < ns 318 | Forb(N) = true; 319 | N = vertcat(Nei{N}); 320 | N = unique_elements(N,Fal); 321 | I = Forb(N); 322 | N = N(~I); 323 | if ~isempty(N) 324 | i = i+1; 325 | Study{i} = N; 326 | StudySize(i) = length(N); 327 | else 328 | Study = Study(1:i); 329 | StudySize = StudySize(1:i); 330 | i = ns+1; 331 | end 332 | end 333 | end 334 | 335 | % Define study as a vector 336 | ns = length(StudySize); 337 | studysize = sum(StudySize); 338 | study = vertcat(Study{:}); 339 | 340 | % Determine the components of study 341 | nc = size(CutComps,1); 342 | i = 1; % index of cut component 343 | j = 0; % number of elements attributed to components 344 | k = 0; % number of study components 345 | Fal(study) = true; 346 | Components = cell(nc,1); 347 | CompSize = zeros(nc,1); 348 | Comp = zeros(studysize,1); 349 | while i <= nc 350 | C = CutComps{i}; 351 | while j < studysize 352 | a = length(C); 353 | Comp(1:a) = C; 354 | Fal(C) = false; 355 | if a > 1 356 | Add = unique_elements(vertcat(Nei{C}),False); 357 | else 358 | Add = Nei{C}; 359 | end 360 | t = a; 361 | I = Fal(Add); 362 | Add = Add(I); 363 | a = length(Add); 364 | while a > 0 365 | Comp(t+1:t+a) = Add; 366 | Fal(Add) = false; 367 | t = t+a; 368 | Add = vertcat(Nei{Add}); 369 | Add = unique_elements(Add,False); 370 | I = Fal(Add); 371 | Add = Add(I); 372 | a = length(Add); 373 | end 374 | j = j+t; 375 | k = k+1; 376 | Components{k} = Comp(1:t); 377 | CompSize(k) = t; 378 | if j < studysize 379 | C = zeros(0,1); 380 | while i < nc && isempty(C) 381 | i = i+1; 382 | C = CutComps{i}; 383 | J = Fal(C); 384 | C = C(J); 385 | end 386 | if i == nc && isempty(C) 387 | j = studysize; 388 | i = nc+1; 389 | end 390 | else 391 | i = nc+1; 392 | end 393 | end 394 | Components = Components(1:k); 395 | CompSize = CompSize(1:k); 396 | end 397 | 398 | % Determine BaseSize and Cont 399 | Cont = true(k,1); 400 | BaseSize = zeros(k,1); 401 | Bases = cell(k,1); 402 | if k > 1 403 | Forb(study) = true; 404 | Fal(study) = false; 405 | Fal(Study{1}) = true; 406 | for i = 1:k 407 | % Determine the size of the base of the components 408 | Set = unique_elements([Components{i}; Study{1}],False); 409 | False(Components{i}) = true; 410 | I = False(Set)&Fal(Set); 411 | False(Components{i}) = false; 412 | Set = Set(I); 413 | Bases{i} = Set; 414 | BaseSize(i) = length(Set); 415 | end 416 | Fal(Study{1}) = false; 417 | Fal(Study{ns}) = true; 418 | Forb(study) = true; 419 | for i = 1:k 420 | % Determine if the component can be extended 421 | Set = unique_elements([Components{i}; Study{ns}],False); 422 | False(Components{i}) = true; 423 | I = False(Set)&Fal(Set); 424 | False(Components{i}) = false; 425 | Set = Set(I); 426 | if ~isempty(Set) 427 | N = vertcat(Nei{Set}); 428 | N = unique_elements(N,False); 429 | I = Forb(N); 430 | N = N(~I); 431 | if isempty(N) 432 | Cont(i) = false; 433 | end 434 | else 435 | Cont(i) = false; 436 | end 437 | end 438 | end 439 | 440 | end % End of function 441 | 442 | 443 | function Class = component_classification(CompSize,Cont,BaseSize,CutSize) 444 | 445 | % Classifies study region components: 446 | % Class(i) == 0 continuation 447 | % Class(i) == 1 branch 448 | 449 | nc = size(CompSize,1); 450 | StudySize = sum(CompSize); 451 | Class = ones(nc,1); % true if a component is a branch to be further segmented 452 | ContiComp = 0; 453 | % Simple initial classification 454 | for i = 1:nc 455 | if BaseSize(i) == CompSize(i) && ~Cont(i) 456 | % component has no expansion, not a branch 457 | Class(i) = 0; 458 | elseif BaseSize(i) == 1 && CompSize(i) <= 2 && ~Cont(i) 459 | % component has very small expansion, not a branch 460 | Class(i) = 0; 461 | elseif BaseSize(i)/CutSize < 0.05 && 2*BaseSize(i) >= CompSize(i) && ~Cont(i) 462 | % component has very small expansion or is very small, not a branch 463 | Class(i) = 0; 464 | elseif CompSize(i) <= 3 && ~Cont(i) 465 | % very small component, not a branch 466 | Class(i) = 0; 467 | elseif BaseSize(i)/CutSize >= 0.7 || CompSize(i) >= 0.7*StudySize 468 | % continuation of the segment 469 | Class(i) = 0; 470 | ContiComp = i; 471 | else 472 | % Component is probably a branch 473 | end 474 | end 475 | 476 | Branches = Class == 1; 477 | if ContiComp == 0 && any(Branches) 478 | Ind = (1:1:nc)'; 479 | Branches = Ind(Branches); 480 | [~,I] = max(CompSize(Branches)); 481 | Class(Branches(I)) = 0; 482 | end 483 | 484 | end % End of function 485 | -------------------------------------------------------------------------------- /testdata.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwang520/SSSC/efef5aaf393b44110de91a86769fd98585d21703/testdata.mat -------------------------------------------------------------------------------- /unique_elements.m: -------------------------------------------------------------------------------- 1 | function Set = unique_elements(Set,False) 2 | 3 | n = length(Set); 4 | if n > 2 5 | I = true(n,1); 6 | for j = 1:n 7 | if ~False(Set(j)) 8 | False(Set(j)) = true; 9 | else 10 | I(j) = false; 11 | end 12 | end 13 | Set = Set(I); 14 | elseif n == 2 15 | if Set(1) == Set(2) 16 | Set = Set(1); 17 | end 18 | end --------------------------------------------------------------------------------