<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Heinrich on Medium]]></title>
        <description><![CDATA[Stories by Heinrich on Medium]]></description>
        <link>https://medium.com/@HeinrichWirth?source=rss-5b1baaab6189------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n5bRj-R2Fy0x0ckYw_SOPw.jpeg</url>
            <title>Stories by Heinrich on Medium</title>
            <link>https://medium.com/@HeinrichWirth?source=rss-5b1baaab6189------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:55:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@HeinrichWirth/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Is There Light at the End of the Tunnel? Checking the Track with LiDAR]]></title>
            <link>https://medium.com/@HeinrichWirth/is-there-light-at-the-end-of-the-tunnel-checking-the-track-with-lidar-b756c2f93697?source=rss-5b1baaab6189------2</link>
            <guid isPermaLink="false">https://medium.com/p/b756c2f93697</guid>
            <category><![CDATA[point-cloud]]></category>
            <category><![CDATA[transportation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[lidar]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Heinrich]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 19:23:23 GMT</pubDate>
            <atom:updated>2026-10-24T19:26:46.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>From 175,688 points to a confirmed obstacle: rail geometry, robust fitting and a 3D walkthrough of a metro hackathon solution</h3><figure><img alt="Is there light at the end of the tunnel? A dense LiDAR cloud coloured by return intensity, with the detected obstacle at 96.96 m." src="https://cdn-images-1.medium.com/proxy/1*E7mUYJ1e1bIM6HEc4M9AWQ.png" /></figure><p>Is there light at the end of the tunnel? Possibly. Our job was to check whether the train would hit anything on its way there :)</p><p>Hello again! When I wrote the Russian version of this article, only a couple of days had passed since <a href="https://medium.com/@HeinrichWirth/to-train-or-to-filter-removing-road-shadows-without-neural-networks-4ff287807502">my article on removing shadows from road images</a>. Yet here was another long post with formulas and pictures. The hackathon problem was so good that I started writing about it during the event. The code was still changing, and the draft was already growing.</p><p>Our task was to detect obstacles in a metro tunnel using LiDAR. The sensor sends out laser pulses and measures distances from their reflections. What comes back is a point cloud: walls, rails, cables, brackets and, perhaps, something that should not be on the track.</p><p>At first, that sounds like a matter of finding the extra object. But the tunnel wall is also large, close and very easy to see. Why is it not an obstacle, while a small object between the rails is?</p><p>To answer that, we first need to know where the train will go. Our obstacle search therefore starts with the rails. We reconstruct the track, place a train envelope along it and check which measured points fall inside.</p><p>This is our team’s solution to the Moscow Transport challenge at the LCT 2026 hackathon. I will focus on the geometry: from the nearby rail pair to an obstacle detection. There is no obstacle-type classifier and no pre-built tunnel map.</p><p>We will follow one episode from a test recording containing synthetic obstacles. Starting with <strong>175,688 points in the current cloud</strong>, we will reconstruct the rails and detect a large square obstacle <strong>96.96 m from the LiDAR</strong>. Another <strong>0.30 s</strong> later, a new measurement batch confirms the detection. That episode will carry us through the main stages; then we will look at a wire hanging from above.</p><figure><img alt="The same section in two projections. Computation uses the original points; the overview is thinned for display." src="https://cdn-images-1.medium.com/proxy/1*P6a9qw41tnls0caM5xjdOA.png" /><figcaption>The same section in two projections. Computation uses the original points; the overview is thinned for display.</figcaption></figure><p>First, we need somewhere sensible to put the search region. The obstacle can wait a little longer.</p><h3>Drawing a rectangle is easy. Putting it in the right place is harder</h3><p>The experiment uses an envelope 2.1 m wide and 3 m high, measured from the railheads. We could point that box straight along the sensor axis and look for points inside. On a straight stretch, the picture might even look convincing.</p><p>But the track bends, its position relative to the sensor changes, and its cross-section can be tilted. The envelope has to follow the rails. Otherwise, on a curve, we will inspect one part of the tunnel while the train travels through another.</p><p>LiDAR gives us successive clouds containing point coordinates and return intensity. It does not provide a ready-made answer saying “the train goes here”. We first find the rails near the sensor, trace the track into the tunnel and only then test the points inside the envelope.</p><figure><img alt="The conductor rail connects the nearby search to track reconstruction farther into the tunnel." src="https://cdn-images-1.medium.com/proxy/1*Hp05gGsqCCHVIs-nQCQAlw.png" /><figcaption>The conductor rail connects the nearby search to track reconstruction farther into the tunnel.</figcaption></figure><p>To trace the conductor rail, we use the current scan and up to 11 preceding clouds. Obstacle testing uses a fresh batch of three clouds. These are different data sets: history helps reconstruct the track, while confirmation of an object must rely on new measurements.</p><h3>Why roughly a metre and a half, rather than two?</h3><p>We have a useful starting point: the structure has known geometry. Rails cannot be placed arbitrarily, and the relevant standards tell us what sort of arrangement to look for.</p><p>The Russian standard specifies a nominal gauge of 1,520 mm on straight metro track, measured between the inner faces of the railheads. Tighter curves allow a wider gauge. That gives us the roughly 1.5 m scale of the rail spacing. These dimensions are specified in <a href="https://meganorm.ru/mega_doc/norm_update_01052026/metodika/0/sp_120_13330_2022_svod_pravil_metropoliteny_snip_32-02-2003.html">SP 120.13330.2022, “Metros”, section 5.7.1.7</a>.</p><figure><img alt="Track gauge is measured between the inner faces. Orange dots schematically indicate the anchors detected by the algorithm." src="https://cdn-images-1.medium.com/proxy/1*fG1XnlW_3ZyOT_d1zeu1-Q.png" /><figcaption>Track gauge is measured between the inner faces. Orange dots schematically indicate the anchors detected by the algorithm.</figcaption></figure><p><strong>The conductor rail sits beside a running rail, with its contact surface above the running-rail heads.</strong> The <a href="https://wiki.nashtransport.ru/wiki/%D0%9F%D0%A2%D0%AD_%D0%BC%D0%B5%D1%82%D1%80%D0%BE%D0%BF%D0%BE%D0%BB%D0%B8%D1%82%D0%B5%D0%BD%D0%BE%D0%B2#%D0%9A%D0%BE%D0%BD%D1%82%D0%B0%D0%BA%D1%82%D0%BD%D1%8B%D0%B9_%D1%80%D0%B5%D0%BB%D1%8C%D1%81">metro operating rules, section 3.26</a> give 690 mm from the inner face of the nearest running-rail head to the conductor-rail axis, and 160 mm vertically from railhead level to its contact surface. So this structure also has a useful expected search region beside the track.</p><p><strong>Clearance standards describe the space required by trains and the placement of surrounding equipment.</strong> For metros, the outlines are specified in <a href="https://normadocs.ru/gost_23961-2024">GOST 23961–2024</a>. The useful idea here is simple: once we have reconstructed the track, we can define a region in which a foreign object would obstruct passage. Our 2.1 × 3 m experimental rectangle is a chosen inspection envelope, rather than a reproduction of every outline in that standard.</p><p>That gives us a sequence: find a plausible rail pair, follow the track and inspect the space along it. Now let us do that with the LiDAR points.</p><h3>1. Collapse the first eight metres into a cross-section</h3><p>Let <strong>s</strong> denote the longitudinal coordinate, <strong>v</strong> the lateral coordinate and <strong>z</strong> height. For the initial search, we use points in the first 8 m. Their longitudinal position is temporarily set aside: we examine the projection onto <strong>(v, z)</strong>.</p><p>Looking at the whole tunnel at once makes the rails easy to lose among everything else. Looking end-on collects the returns from several metres of rail into one cross-sectional profile. That is a much more convenient object to search for.</p><p>We divide the cross-section into 5 mm cells and count the points in each. Then we smooth the histogram with a Gaussian scale of 25 mm. In grid units:</p><figure><img alt="Equation: \sigma_{\mathrm{grid}}=\frac{0.025}{0.005}=5\mathrm{\ cells}" src="https://cdn-images-1.medium.com/proxy/1*TmlNRiZW8oGbmm337F0k5Q.png" /></figure><p>We can now find local density maxima. A maximum is not necessarily a railhead, though. A lower part of the structure may produce more returns than the top surface we need.</p><h3>Turn a dense patch into a candidate</h3><p>Around each maximum, we collect points within an 85 mm radius. The candidate’s lateral coordinate is their median; its height is their 75th percentile:</p><figure><img alt="Equation: \hat v=\operatorname{median}(v_i),\qquad \hat z=Q_{0.75}(z_i)" src="https://cdn-images-1.medium.com/proxy/1*OIf2h-j57bt5T5pFiX2FrA.png" /></figure><p>The median is less easily pulled sideways by an isolated outlier. The upper quartile moves the height estimate towards the top of the cluster without jumping to its single highest point.</p><p>Support decreases with distance from the density maximum <strong>m</strong>:</p><figure><img alt="Equation: a=\sum_i\exp\left(-\frac{\Vert p_i-m\Vert^2}{2\cdot 0.025^2}\right)" src="https://cdn-images-1.medium.com/proxy/1*yMb8Tl4dH7Zg7SRkzx55DA.png" /></figure><p>Here, <strong>pᵢ = (vᵢ, zᵢ)</strong>, with coordinates in metres. A point 25 mm from the maximum contributes about <strong>0.607</strong>; at 50 mm, it contributes <strong>0.135</strong>. Two neighbouring clusters should not receive equal influence merely because both fall inside a broad search region.</p><p>Next comes the top-surface check. Within a band of ±55 mm laterally and ±20 mm vertically, we require at least eight points and a continuous run of three occupied 10 mm cells. A cell is occupied when it contains at least two points.</p><p>We are looking for a small, supported patch of surface. One conveniently placed outlier will not do.</p><figure><img alt="Rectangles mark the support bands of the selected heads. Grey circles in the lower panel are other candidates." src="https://cdn-images-1.medium.com/proxy/1*S8WfYvGa_jeNYp24HtMHYg.png" /><figcaption>Rectangles mark the support bands of the selected heads. Grey circles in the lower panel are other candidates.</figcaption></figure><h3>Choose the pair together</h3><p>We now have several patches that resemble railheads. Choosing the best one on the left and then the best one on the right sounds natural. Together, however, they may make a completely implausible pair. We therefore evaluate whether two candidates can belong to the same track.</p><p>For the left and right candidates:</p><figure><img alt="Equation: \begin{aligned}g&amp;=v_{\mathrm{R}}-v_{\mathrm{L}},\\ c&amp;=\frac{v_{\mathrm{L}}+v_{\mathrm{R}}}{2},\\ h&amp;=\frac{z_{\mathrm{L}}+z_{\mathrm{R}}}{2},\\ \Delta z&amp;=z_{\mathrm{R}}-z_{\mathrm{L}}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*In8742NE48Bsw8HMinEGLQ.png" /></figure><p><strong>g</strong> is their lateral separation, <strong>c</strong> their midpoint, <strong>h</strong> their mean height and <strong>Δz</strong> their height difference. Subscripts L and R denote left and right.</p><p>Hard constraints come first: <strong>|c| ≤ 0.30 m</strong>, <strong>1.30 ≤ g ≤ 1.80 m</strong>, and <strong>|Δz| ≤ 0.18 m</strong>. We then rank the surviving pairs.</p><p>The score combines support on both sides, its balance, surface quality and departures from the expected nearby geometry. The rail-spacing penalty, for example, is:</p><figure><img alt="Equation: \begin{aligned}P_g&amp;=0.12\left(\frac{g-1.56745}{0.07}\right)^2+2\left(\frac{e}{0.07}\right)^2,\\e&amp;=\max(1.48-g;\;0;\;g-1.62).\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*lGKOohPAohh881BphVwvvQ.png" /></figure><p>The 1.56745 m reference was chosen from the data used to configure the detector and is rounded here for readability. The first term gently prefers separations near it; the second penalises distances outside 1.48–1.62 m more strongly. The measured separation <strong>g</strong> itself does not change: the penalty only affects which pair wins.</p><p>At <strong>g = 1.60 m</strong>, the penalty is about <strong>0.026</strong>. At <strong>g = 1.70 m</strong>, it is about <strong>3.04</strong>. Both pairs pass the broad hard filter, but the second would need much stronger support to win.</p><p>Now let us combine the remaining evidence: how well we see both heads, whether they resemble surfaces and how plausible their positions are. It is a long formula, but each term has a small job.</p><p>Supports <strong>a</strong> and <strong>b</strong> are capped at 80. The surface-quality scores <strong>q₁</strong> and <strong>q₂</strong> lie between zero and one, while <strong>σ₁</strong> and <strong>σ₂</strong> describe cluster spread in metres:</p><figure><img alt="Equation: \begin{aligned}S={}&amp;0.4\,[\ln(1+a)+\ln(1+b)]\\&amp;+0.15\,\frac{\min(a,b)}{\max(a,b)}+0.4\,(q_1+q_2)\\&amp;-P_g-0.12\left(\frac{c}{0.30}\right)^2\\&amp;-0.08\left(\frac{h+1.09348}{0.35}\right)^2\\&amp;-0.10\left(\frac{\Delta z}{0.18}\right)^2-0.25\,\frac{\sigma_1+\sigma_2}{0.05}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*K94tAlB_y8OkK_nSoF09-A.png" /></figure><p>Surface quality is <strong>min(1, N / 20) · min(1, K / 6)</strong>, where <strong>N</strong> is the number of points in the band and <strong>K</strong> the length of its continuous run of occupied cells. Cluster spread is the square root of the largest eigenvalue of the point covariance matrix.</p><p>The logarithm and support cap prevent one very dense patch from overwhelming geometry indefinitely. The balance term favours a pair with evidence on both sides.</p><p>Our scan has four candidates on the left and five on the right. Three lower pairs are displaced by supported upper alternatives; three admissible pairs remain after filtering. The selected heads are:</p><figure><img alt="Equation: \begin{aligned}(v_{\mathrm{L}},z_{\mathrm{L}})&amp;=(-0.77309;\;-1.09447)\mathrm{\ m},\\(v_{\mathrm{R}},z_{\mathrm{R}})&amp;=(0.78769;\;-1.08519)\mathrm{\ m},\\g&amp;=1.56079\mathrm{\ m},\qquad \Delta z=9.27\mathrm{\ mm}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*g0p40tddneEHwr__Tn5F9A.png" /></figure><p>Their surface bands contain 408 and 412 points. The pair scores <strong>S = 4.2103</strong>, with a margin <strong>ΔS = 1.1884</strong> over the alternative. This is the pair passed to the next stage.</p><p>A further safeguard handles lower structures: an upper candidate can displace a lower one only if it has sufficient support and remains compatible with <strong>the same opposite rail</strong>. Simply taking the two highest points would be suspiciously convenient :)</p><p>Even the best pair might only be slightly better than another, nearly identical one. We check both its own support and its margin over the alternative:</p><figure><img alt="Equation: \kappa=\left(1-\exp\left(-\frac{a_{\min}}{20}\right)\right)\left(1-\exp\left(-\frac{\Delta S}{0.25}\right)\right)" src="https://cdn-images-1.medium.com/proxy/1*sKuHjm1ZkwNjGFsreYMcuw.png" /></figure><p><strong>aₘᵢₙ</strong> is the smaller of the two original support values, before capping; <strong>ΔS</strong> is the margin over the best distinct pair. If there is no such alternative, ΔS is set to 3. Results with <strong>κ &lt; 0.25</strong> are rejected. This is a heuristic confidence score, not a probability of correctness.</p><h3>2. Find the conductor rail by its profile</h3><p>The nearby running rails give us a reference. Next we look beside them for the conductor rail. We know its cross-sectional shape and approximately where to expect it relative to a running rail.</p><p>The template is a set of points <strong>T = {tⱼ}</strong>. On each side, we express observations relative to the detected head, with the lateral axis pointing outwards from the track. This lets us use the same template on the left and right.</p><figure><img alt="Left: the profile beside the detected running rail. Right: the fitting region, with observations in teal and the template in gold." src="https://cdn-images-1.medium.com/proxy/1*1rg7JkNzz7Wu1IuWL0X5tA.png" /><figcaption>Left: the profile beside the detected running rail. Right: the fitting region, with observations in teal and the template in gold.</figcaption></figure><p>The nearby fit optimises <strong>two translations</strong>, with no free template rotation. Write them as <strong>a = (d, h)</strong>: lateral and vertical offsets relative to the running rail.</p><p>The expected position and deviation scales are:</p><figure><img alt="Equation: \begin{aligned}\mu&amp;=(0.63344;\;0.25559)\mathrm{\ m},\\\sigma&amp;=(0.035;\;0.055)\mathrm{\ m}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*MqHGTEqA2nKOeCv9G03yPQ.png" /></figure><p>The admissible region is broader: lateral offsets from 0.49 to 1.29 m, and vertical offsets from −0.12 to 0.58 m. The expected position guides the search without forcing it to return one predefined point.</p><h3>First, fit the template</h3><p>Imagine laying the profile contour onto the cross-section and shifting it sideways and vertically. We want the position at which the observations lie closest to the contour. For an observed point <strong>pᵢ</strong>, the distance to the translated template is:</p><figure><img alt="Equation: \delta_i(a)=\min_j\Vert p_i-(t_j+a)\Vert" src="https://cdn-images-1.medium.com/proxy/1*LvoA7I9eIzqXpbjot7AR_Q.png" /></figure><p>Normalise that distance by 15 mm, then add two residuals that favour the expected position:</p><figure><img alt="Equation: \begin{aligned}r_i(a)&amp;=\frac{\delta_i(a)}{0.015},\\r_d(a)&amp;=0.1\sqrt{N}\,\frac{d-\mu_d}{\sigma_d},\\r_h(a)&amp;=0.1\sqrt{N}\,\frac{h-\mu_h}{\sigma_h}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*oBPnBGYVeyPobv8pgORHVg.png" /></figure><p><strong>N</strong> is the number of points in the fitting region. The √N factor keeps the positional constraint on a comparable scale as the observation count changes.</p><p>The optimisation uses unique points near the expected profile: its bounding box is expanded by 15 mm, then by another 40 mm to provide fixed context. We select this set before optimisation and keep it fixed as the template moves. Candidate evaluation later uses all unique points in the admissible search region.</p><p>The optimiser minimises a Cauchy loss over all those residuals:</p><figure><img alt="Equation: a^*=\underset{a}{\operatorname{arg\,min}}\;\frac{1}{2}\sum_k\ln\left(1+r_k(a)^2\right)" src="https://cdn-images-1.medium.com/proxy/1*0Mvtzr3kksWLg_jsD79s6A.png" /></figure><p>That includes both the distance residuals and the two positional residuals. There is no separate purely quadratic position penalty in this fit.</p><p>Why Cauchy? An error of 15 mm gives a normalised residual of 1; 60 mm gives 4. A quadratic loss would grow from <strong>0.5 to 8</strong>. Here, it grows from <strong>0.347 to 1.417</strong>. A distant unrelated point can still influence the fit, but it does not get to run the meeting.</p><figure><img alt="Both losses favour close fits. At large errors, Cauchy reduces an individual point’s influence much more strongly." src="https://cdn-images-1.medium.com/proxy/1*CPQcltF2mnbLMOQBMFUFdg.png" /><figcaption>Both losses favour close fits. At large errors, Cauchy reduces an individual point’s influence much more strongly.</figcaption></figure><p>We start the fit from two positions: the expected location and the median of the selected observations. Then we score the resulting candidates. Fitting a translation and deciding which candidate to accept are separate operations with different objectives.</p><h3>A close fit is not the whole story</h3><p>Once the optimiser has found a translation, we assess its position, agreement with the profile and coverage. First, how far did it move from the expected location?</p><figure><img alt="Equation: G=\exp\left\{-\frac{1}{2}\left[\left(\frac{d-\mu_d}{\sigma_d}\right)^2+\left(\frac{h-\mu_h}{\sigma_h}\right)^2\right]\right\}" src="https://cdn-images-1.medium.com/proxy/1*7KiBP9WsElCs3oze4CLyZw.png" /></figure><p>At the expected position, <strong>G = 1</strong>. Moving 35 mm sideways with no height change gives <strong>G ≈ 0.607</strong>; moving 70 mm gives <strong>0.135</strong>.</p><p>The second term measures shape agreement. Among points inside the template’s bounding box, with a small margin, sort the distances and retain the best 60%:</p><figure><img alt="Equation: \begin{aligned}m&amp;=\max\left(1,\left\lfloor0.6N_{\mathrm{in}}\right\rfloor\right),\\D&amp;=\frac{1}{m}\sum_{j=1}^{m}\min\left(\delta_{(j)},0.5\right),\\O&amp;=\exp\left(-\frac{D}{0.015}\right).\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*AT5oiucoSgDFYgi7g5AhcQ.png" /></figure><p>The <strong>δ₍ⱼ₎</strong> values are sorted distances; <strong>D</strong> is their trimmed mean in metres. The 0.5 m cap applies to each distance in the sum.</p><p>Why not average every point? Nearby hardware also enters the search region, and we do not want to force it onto the conductor profile. But trimming creates the opposite problem: a few lucky points might fit one tiny piece of the template while leaving the rest empty.</p><p>The third term therefore looks in the reverse direction, <strong>from the template to the observations</strong>:</p><figure><img alt="Equation: \begin{aligned}D_{\mathrm{rev}}&amp;=\frac{1}{M}\sum_j\min_i\Vert t_j+a-p_i\Vert,\\\tau&amp;=\max(\Delta,1.5\ell),\qquad C=\exp\left(-\frac{D_{\mathrm{rev}}}{\tau}\right).\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*5XbnCQ1ZFlsE_8H7_69z4g.png" /></figure><p><strong>M</strong> is the number of points in the thinned template, <strong>Δ</strong> the original template grid spacing, and <strong>ℓ</strong> the characteristic observation spacing. With at least three observations, ℓ is the median distance to the second-nearest neighbour, excluding the point itself. Coverage is thus evaluated relative to cloud density.</p><p>The final score is:</p><figure><img alt="Equation: S=1.12G+O+0.35C" src="https://cdn-images-1.medium.com/proxy/1*WBihtcDUG00d4LZqy2xNtA.png" /></figure><p>In our scan, the conductor rail is on the <strong>right</strong>. Its fitted offset from the running-rail head is:</p><figure><img alt="Equation: a^*=(0.622967;\;0.269962)\mathrm{\ m}" src="https://cdn-images-1.medium.com/proxy/1*X3bBeIriFKny9OnTR-89hQ.png" /></figure><p>The trimmed mean distance to the template is <strong>D = 1.543 mm</strong>, and the coverage scale is <strong>τ = 7.050 mm</strong>. This gives:</p><figure><img alt="Equation: \begin{aligned}G&amp;=0.92417,\quad O=0.90224,\quad C=0.76738,\\S&amp;=1.12\cdot0.92417+0.90224+0.35\cdot0.76738\\&amp;\approx2.20589.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*JFC-PnSetR0eN8gQHay8tg.png" /></figure><figure><img alt="The observations fit the shape well but do not cover it completely. Shape agreement and coverage therefore receive different scores." src="https://cdn-images-1.medium.com/proxy/1*sUvGo_kMW4ZQO-_OJjouhg.png" /><figcaption>The observations fit the shape well but do not cover it completely. Shape agreement and coverage therefore receive different scores.</figcaption></figure><p>The profile is supported by <strong>1,233 original returns</strong>, representing <strong>635 unique points</strong> in the cross-sectional projection. Different measurements can share the same projected coordinates. For shape evaluation, duplicates do not become new geometric evidence.</p><p>Support and candidate ambiguity are checked as well. If two comparable candidates lie on opposite sides of the track, the detector can return an ambiguous result. In this episode, the right-hand profile is accepted.</p><p>We now have a specific profile, position and set of supporting returns. The next job is to keep following that same structure into the tunnel.</p><h3>3. Follow the profile, checking every join</h3><p>The nearby conductor rail has been found. One long straight line would soon stop matching a curved track, so we proceed through overlapping <strong>8 m windows</strong>, normally advancing <strong>4 m</strong> at a time. Each new window gets another profile fit.</p><p>The main direction estimate uses already confirmed points from the current scan over the preceding eight metres. Sparse regions have an additional direction-refinement step, which we will reach shortly.</p><p>We estimate direction with the principal component:</p><figure><img alt="Equation: \begin{aligned}\bar p&amp;=\frac{1}{N}\sum_i p_i,\\Q&amp;=\frac{1}{N}\sum_i(p_i-\bar p)(p_i-\bar p)^{\mathsf{T}}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*_nDmflKwQonXRVNY34_I6w.png" /></figure><p><strong>t</strong> is the eigenvector of <strong>Q</strong> associated with its largest eigenvalue. An elongated cluster defines a longitudinal axis. We align its sign with the previous direction; a sudden local turn greater than 5° is not accepted as an ordinary continuation.</p><figure><img alt="Teal points are accepted conductor-rail measurements; gold marks the anchors. All three panels use the same background and scales." src="https://cdn-images-1.medium.com/proxy/1*HDoHQHaC-zNEJIffMmcySw.png" /><figcaption>Teal points are accepted conductor-rail measurements; gold marks the anchors. All three panels use the same background and scales.</figcaption></figure><h3>The new profile must explain the old points</h3><p>Overlap is not just spare room. We have already observed the conductor rail in the shared region. If the new fit jumps to another structure, this is where the disagreement should show up.</p><p>Let <strong>dᵢ</strong> be the distances from previously supported points in the overlap to the new profile. The main statistic is their 90th percentile:</p><figure><img alt="Equation: d_{90}=Q_{0.90}\left(\{d_i\}\right)" src="https://cdn-images-1.medium.com/proxy/1*s9Jwtu6O00nCwnSvw6TotA.png" /></figure><p>Overlap is good when <strong>d₉₀ ≤ 30 mm</strong>. A weaker match is allowed with <strong>d₉₀ ≤ 50 mm</strong>, provided a clipped root-mean-square distance also passes:</p><figure><img alt="Equation: \sqrt{\frac{1}{N}\sum_i\min(d_i,0.06)^2}\leq0.04\mathrm{\ m}" src="https://cdn-images-1.medium.com/proxy/1*hw1qjbuq6rsLk8nHXna7cQ.png" /></figure><p>Each distance is capped at 60 mm before squaring. That reduces the effect of isolated distant points, while the 90th-percentile test prevents widespread disagreement from being excused.</p><p>For example, <strong>d₉₀ = 24 mm</strong> passes the good-overlap test. A value of <strong>42 mm</strong>, with a clipped RMS of <strong>31 mm</strong>, is weaker but acceptable. The same <strong>42 mm</strong> with an RMS of <strong>43 mm</strong> fails. These illustrate threshold decisions; they are not recording statistics.</p><p>The new region is checked too: at least three unique supporting points within 20 mm of the profile, plus limits on shape error, displacement and separation from competing candidates.</p><p>A small local fitting error proves very little by itself. A template may fit neighbouring hardware beautifully. Explaining the previous section with that same template is harder.</p><h3>Handle a weak section without inventing a track</h3><p>It would be convenient to have exactly one good profile in every window. Sparse returns and similar nearby structures make that unlikely. The search therefore retains up to three distinct hypotheses, with some anchors temporarily marked tentative.</p><p>To confirm a sequence, we fit a quadratic spatial curve to recent confirmed and tentative anchors. For each coordinate:</p><figure><img alt="Equation: c(u)=a_0+a_1u+a_2u^2" src="https://cdn-images-1.medium.com/proxy/1*PgwzmkxftpaVyYklk2xYZw.png" /></figure><p><strong>u</strong> is the normalised longitudinal coordinate, and the coefficients are found by least squares. Confirmation needs at least three anchors spanning at least 2 m, support from unique measurements, and deviations of no more than 50 mm for every anchor used in the fit.</p><p>Tentative sections cannot accumulate forever. More than two without confirmation terminates that branch. Local uncertainty may be resolved by later measurements; it cannot grow into a track drawn all the way to the horizon.</p><h3>What if there is a gap between returns?</h3><p>Distant returns do not have to fill every four-metre strip evenly. A window may be almost empty even though the profile becomes visible again a little farther ahead. Stopping there would lose the rail because of the scanning pattern.</p><p>If fewer than three unique cross-sectional points survive filtering, we test two more window positions, 4 and 8 m farther ahead. It is the same search with the same template. We add no invented measurements to the gap, and the profile found beyond it must still pass the shape checks and subsequent anchor confirmation.</p><p>Direction can become stale across the gap too. After a long gap, the last three detected anchors, including a tentative one, guide the next window. If the new fit disagrees with the overlap, we try refining direction from the combined support of the old and new profiles, then fit again. The turn limit and consistency checks remain. Otherwise, recovering from a gap would become permission to search anywhere.</p><h3>Align history before using it</h3><p>When the current scan is insufficient, we add available preceding clouds, up to 12 scans in the history window. The sensor has moved between them, so their coordinates must first be brought into one frame.</p><p>Let <strong>Hᵢ</strong> map points from scan i into a common coordinate system. In homogeneous coordinates:</p><figure><img alt="Equation: p_T=H_T^{-1}H_i p_i" src="https://cdn-images-1.medium.com/proxy/1*pa9xYpErD-9fRswqrwmkcQ.png" /></figure><p>We first transform an old point into the common frame, then into the current sensor frame. Without rotation, a simple example is enough: an object was 20 m ahead, and the sensor moved 2 m towards it. The old point should now lie at 18 m. Leaving it at 20 m would stretch the object along the direction of travel.</p><figure><img alt="Both panels use the same points from the first new window. Colour indicates measurement age, not object class." src="https://cdn-images-1.medium.com/proxy/1*TPCSoBsGIKKaQX79Omn_eg.png" /><figcaption>Both panels use the same points from the first new window. Colour indicates measurement age, not object class.</figcaption></figure><p>We use sensor poses available at processing time. Only the current and preceding clouds enter the geometry search.</p><p>In this episode, the search takes <strong>20 steps</strong>, yielding <strong>21 anchors</strong> including the initial one. The conductor line is supported by <strong>8,742 original measurements</strong>: <strong>1,948 from the current scan</strong> and <strong>6,794 from earlier scans</strong>. Its farthest confirmed point is about <strong>109.44 m</strong> from the sensor.</p><p>History is doing real work here. Most of the support in this section came from previous observations.</p><p>We have followed the conductor rail into the tunnel, but we still have discrete spatial anchors. Building cross-sections directly on those would turn small positional errors into a constantly twitching train envelope.</p><h3>4. Turn the anchors into a smooth spatial curve</h3><p>Joining the anchors with straight segments is easy. Unfortunately, every small anchor error then becomes a jump in direction, which rotates the entire train envelope. A few centimetres no longer look so harmless.</p><p>We therefore smooth the line before reconstructing the running rails. First, longitudinally close anchors are merged within 25 cm. The curve is then represented by a cubic B-spline, with interior knots every 4 m:</p><figure><img alt="Equation: c(s)=\sum_j B_j(s)a_j" src="https://cdn-images-1.medium.com/proxy/1*2X7vJxPa1jXrXg2J2ep1Vg.png" /></figure><p><strong>Bⱼ(s)</strong> are the spline basis functions and <strong>aⱼ</strong> the unknown 3D coefficients. We do not force the spline through every anchor: that would reproduce the measurement errors as faithfully as the track.</p><h3>What the fit minimises</h3><p>For one coordinate, let <strong>y</strong> contain the observations, <strong>a</strong> the coefficients and <strong>Xᵢⱼ = Bⱼ(sᵢ)</strong> the basis values at the anchor positions. The prediction is <strong>Xa</strong>.</p><p>Second and third derivatives are evaluated on a 0.5 m grid. For the two horizontal coordinates, the regularisation penalty is:</p><figure><img alt="Equation: \Vert La\Vert^2=\left\Vert\frac{D_2a}{0.025}\right\Vert^2+\left\Vert\frac{D_3a}{0.004}\right\Vert^2" src="https://cdn-images-1.medium.com/proxy/1*jIDi6iXjq3Gm1POvoVND2g.png" /></figure><p><strong>D₂</strong> and <strong>D₃</strong> are the second- and third-derivative matrices of the basis. For the vertical coordinate, both derivatives use a configured scale of about <strong>0.00405</strong>, in their respective derivative units.</p><p>The second derivative penalises bending; the third penalises rapid changes in bending. This discourages the curve from following every small anchor fluctuation. It does not impose a hard minimum turning radius: the penalty acts on coordinate derivatives with respect to the longitudinal parameter.</p><p>At one iteration, the full objective is:</p><figure><img alt="Equation: \begin{aligned}a^*&amp;=\underset{a}{\operatorname{arg\,min}}\left[\Vert W(Xa-y)\Vert^2+\Vert La\Vert^2\right],\\W_{ii}&amp;=\frac{\sqrt{w_i}}{\sigma_i}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*eOaweiKUO3_ufsYYZH9yNw.png" /></figure><p><strong>σᵢ</strong> sets the measurement-uncertainty scale, while <strong>wᵢ</strong> reduces the influence of an inconsistent anchor. The initial measurement model uses a standard deviation of 35 mm on each axis.</p><p>Appending the regularisation rows gives one least-squares system:</p><figure><img alt="Equation: \left[\genfrac{}{}{0}{}{WX}{L}\right]a\approx\left[\genfrac{}{}{0}{}{Wy}{0}\right]" src="https://cdn-images-1.medium.com/proxy/1*jG0XEw7qWXX-khhzxyTmlQ.png" /></figure><p>The upper part asks the curve to stay close to the data; the lower part asks it not to become unnecessarily wiggly.</p><h3>Keep one poor anchor from bending the whole track</h3><p>After fitting, we calculate each anchor’s normalised spatial residual:</p><figure><img alt="Equation: \begin{aligned}r_i&amp;=\sqrt{\sum_{k\in\{x,y,z\}}\left(\frac{\hat c_{ik}-p_{ik}}{\sigma_{ik}}\right)^2},\\w_i&amp;=\max\left(10^{-5},\min\left(1,\frac{1.5}{\max(r_i,\varepsilon)}\right)\right).\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*bj913JQDFsyujLJndEI3yQ.png" /></figure><p><strong>ĉᵢ</strong> is the current curve estimate at the anchor, <strong>pᵢ</strong> the measured anchor and <strong>ε = 10⁻¹²</strong> prevents division by zero. These are Huber weights, with a numerical floor of 10⁻⁵. All three coordinates of an anchor share its weight.</p><p>The initial fit is ordinary least squares, <strong>Xa ≈ y</strong>, without regularisation. Its residuals give the first weights. We then solve the regularised problem and repeat the weight calculation.</p><p>At <strong>r = 1</strong>, the weight stays at one. At <strong>r = 3</strong>, it is <strong>0.5</strong>; at <strong>r = 6</strong>, <strong>0.25</strong>. The implementation performs six such reweighted iterations.</p><figure><img alt="Consistent anchors retain full weight. A large residual reduces an anchor’s influence on the next fit." src="https://cdn-images-1.medium.com/proxy/1*fuF2kmQ7_JBeke2XkC-Ztg.png" /><figcaption>Consistent anchors retain full weight. A large residual reduces an anchor’s influence on the next fit.</figcaption></figure><p>On the full-scale plot, the fitted curve is very close to our actual anchors. A separate plot of anchor-to-curve distances in millimetres makes the changes visible.</p><figure><img alt="Median anchor-to-curve distance: 9.77 mm; maximum: 31.86 mm. These measure the fitting adjustment, not error against a ground-truth track." src="https://cdn-images-1.medium.com/proxy/1*P9c7DHfamgR6Ai7R3he0Rw.png" /><figcaption>Median anchor-to-curve distance: 9.77 mm; maximum: 31.86 mm. These measure the fitting adjustment, not error against a ground-truth track.</figcaption></figure><p>The conductor line now provides a smooth position and direction wherever we need a cross-section. Time to recover the two running rails.</p><h3>5. Reconstruct the running rails from the conductor rail</h3><p>We have traced the conductor rail into the tunnel and located both running-rail heads near the sensor. Their relative arrangement lets us recover the running rails farther ahead.</p><p>Track construction constrains the problem: the two running heads and the conductor profile are related by lateral distances and heights. We do not have to solve each new cross-section from scratch. Simply adding one “standard distance” is not enough, though: the section can be tilted, and the track itself bends.</p><p><strong>We first estimate the relative arrangement nearby, then transport it along the conductor line.</strong> Known geometry supplies search references; the specific offsets and tilt come from nearby measurements.</p><p>In one local cross-section, our example requires moving <strong>0.622 m towards the track and 0.271 m down along the section normal</strong> from the conductor anchor to the nearer railhead. The other head lies a further <strong>1.583 m</strong> across the track. Both heads happen to have the same local height here; the general formula allows separate vertical offsets.</p><figure><img alt="The local cross-section uses dimensions from this calculation. Anchor separation differs from the nominal gauge measured between inner rail faces." src="https://cdn-images-1.medium.com/proxy/1*z6XaSbHmF5HTdKFJgppiRg.png" /><figcaption>The local cross-section uses dimensions from this calculation. Anchor separation differs from the nominal gauge measured between inner rail faces.</figcaption></figure><p>This is the small geometric template that travels along the conductor line. Its position and orientation change at every step.</p><h3>Turn the cross-section with the track</h3><p>We know the conductor line, but which direction should “sideways” mean at each point? On straight track, adding the same global-X offset might seem fine. On a bend, the cross-track direction turns with the track.</p><p>At each position, we build an orthonormal frame <strong>(t, e₁, e₂)</strong>: a tangent and two transverse axes. To avoid unnecessary rotation about the tangent, we transport those axes using the smallest rotation between consecutive tangent directions. This is a Bishop frame.</p><p>For previous and new unit tangents <strong>t₀</strong> and <strong>t₁</strong>:</p><figure><img alt="Equation: \begin{aligned}v&amp;=t_0\times t_1,\qquad c=t_0\cdot t_1,\\R&amp;=I+K+\frac{K^2}{1+c},\qquad Kx=v\times x.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*gEvuGqUWNRUimg4TMLUABQ.png" /></figure><p><strong>K</strong> is the skew-symmetric cross-product matrix and <strong>I</strong> the identity. This rotation maps t₀ to t₁. We apply it to the previous transverse axis, remove its small numerical component along the new tangent and normalise. A cross product supplies the other transverse axis.</p><p>Almost-opposite tangents make the denominator degenerate. The implementation rejects that transition: a sudden 180° reversal should not masquerade as ordinary frame transport.</p><p>Cross-sectional tilt is represented separately by <strong>α</strong>:</p><figure><img alt="Equation: \begin{aligned}b&amp;=\cos\alpha\cdot e_1+\sin\alpha\cdot e_2,\\n&amp;=-\sin\alpha\cdot e_1+\cos\alpha\cdot e_2.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*Ru-lBBWs_-P0ojOdCwqMeQ.png" /></figure><p><strong>b</strong> is the section’s lateral axis; <strong>n</strong> is its perpendicular height axis in the same transverse plane. This separates bending of the line from rail tilt relative to the transported frame.</p><h3>Write the geometry as vectors</h3><p>Nearby observations give five parameters: tilt <strong>α</strong>, lateral distance <strong>d</strong> to the nearer head, vertical offsets <strong>h₁</strong> and <strong>h₂</strong>, and head separation <strong>g</strong>.</p><p>To measure them, we project the nearby heads into cross-sectional planes of the smoothed conductor line. From the vector between heads, remove the component along the tangent, choose its sign according to the conductor-rail side and normalise. This gives <strong>b</strong>, then <strong>n = t × b</strong>.</p><p>For nearer and farther heads <strong>r₁</strong>, <strong>r₂</strong>, and conductor point <strong>c</strong> in that section:</p><figure><img alt="Equation: \begin{aligned}\alpha&amp;=\operatorname{atan2}(b\cdot e_2,b\cdot e_1),\\d&amp;=q(c-r_1)\cdot b,\qquad g=q(r_1-r_2)\cdot b,\\h_1&amp;=(c-r_1)\cdot n,\qquad h_2=(c-r_2)\cdot n.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*k2f24_AtfSQGsGBB53yaRA.png" /></figure><p>The side sign <strong>q</strong> is +1 for a conductor rail on the right and −1 on the left. Parameters are estimated in nearby sections and combined with a coordinate-wise median. A linear fit over longitudinal positions estimates the tilt trend.</p><p>For a conductor-line point <strong>c</strong>, the reconstructed heads are:</p><figure><img alt="Equation: \begin{aligned}r_1&amp;=c-qd\cdot b-h_1\cdot n,\\r_2&amp;=c-q(d+g)\cdot b-h_2\cdot n.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*rBE-NmIp_bdFn0N4gGpKKw.png" /></figure><p>All distances are measured in the local cross-section. We have just recovered them from nearby observations; now the inverse transformation builds heads along the extended line.</p><figure><img alt="Circles in the cross-sections are running-rail heads; squares are conductor anchors. Coordinates are relative to the current LiDAR." src="https://cdn-images-1.medium.com/proxy/1*CTgl-bWIfzn8cXhqadyofg.png" /><figcaption>Circles in the cross-sections are running-rail heads; squares are conductor anchors. Coordinates are relative to the current LiDAR.</figcaption></figure><p>After relating our nearby observations to the smoothed line, the parameters are:</p><figure><img alt="Parameter | Value; Initial section tilt α₀ | 0.349°; Lateral distance d | 0.62194 m; Vertical offsets h₁ and h₂ | 0.27127 m; Railhead separation g | 1.58306 m" src="https://cdn-images-1.medium.com/proxy/1*ro6FeyU8J6vI4Z3zxkdbsg.png" /></figure><p>The head separation differs slightly from the initial 1.56079 m. That first estimate came from a single cross-sectional projection of an eight-metre section. This estimate uses individual 3D sections and their positions relative to the smoothed line.</p><p>The conductor point and frame orientation change as we advance. These relative dimensions therefore produce two spatial curves, rather than two lines with fixed global-X offsets.</p><h3>Do not extrapolate tilt as an endless straight line</h3><p>The nearby region gives an initial tilt <strong>α₀</strong> and a tilt trend <strong>vα</strong>. Lateral and vertical offsets remain constant farther ahead, while the tilt trend gradually fades.</p><p>Measure distance from the end of the nearby region:</p><figure><img alt="Equation: \begin{aligned}\ell&amp;=\max(s-8,0),\\\eta&amp;=\frac{\ell^3}{\ell^2+2^2},\quad \xi=\min\left(\frac{\eta}{L},1\right),\quad L=50\mathrm{\ m},\\\alpha(s)&amp;=\alpha_0+v_{\alpha}\cdot L\left(\xi-\xi^2+\frac{\xi^3}{3}\right).\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*9P-O7kJTFcgMbRCQ41HLmg.png" /></figure><p>Distances in η are in metres; 2² is the square of a 2 m scale. <strong>ξ</strong> is dimensionless. Near the boundary, η grows as ℓ³, so the tilt and its first two derivatives join smoothly to the constant nearby estimate.</p><p>Farther ahead, the cubic <strong>f(ξ) = ξ − ξ² + ξ³/3</strong> takes over. Its derivative is:</p><figure><img alt="Equation: f&#39;(\xi)=(1-\xi)^2" src="https://cdn-images-1.medium.com/proxy/1*kDwJ3jxfV2NSYuUwfCovCQ.png" /></figure><p>As ξ approaches one, the change fades. The total addition is capped at <strong>vαL/3</strong> instead of extrapolating the nearby trend forever.</p><p>For an illustrative <strong>vα = 0.02°/m</strong>, the limiting addition is about <strong>0.333°</strong>. Linear continuation over 100 m would add <strong>2°</strong>.</p><figure><img alt="A nearby tilt trend should not accumulate indefinitely beyond the observed region." src="https://cdn-images-1.medium.com/proxy/1*gZ1g73CNUu87AkVGmc0Q9g.png" /><figcaption>A nearby tilt trend should not accumulate indefinitely beyond the observed region.</figcaption></figure><h3>6. How far does an angular error move a railhead?</h3><p>A centimetre of error in the conductor line shifts both reconstructed heads. An error in section tilt moves them differently: the farther head has a longer lever arm.</p><p>We can quantify that with derivatives of the reconstruction formulas. Collect the section parameters into <strong>x = (α, d, h₁, g, h₂)</strong>, using radians for α. For the nearer head:</p><figure><img alt="Equation: \begin{aligned}\frac{\partial r_1}{\partial\alpha}&amp;=-qd\cdot n+h_1\cdot b,\\\frac{\partial r_1}{\partial d}&amp;=-q\cdot b,\qquad \frac{\partial r_1}{\partial h_1}=-n,\\\frac{\partial r_1}{\partial g}&amp;=0,\qquad \frac{\partial r_1}{\partial h_2}=0.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*F9TJ_1KpU0uFzVZi9frMGQ.png" /></figure><p>For the farther head:</p><figure><img alt="Equation: \begin{aligned}\frac{\partial r_2}{\partial\alpha}&amp;=-q(d+g)\cdot n+h_2\cdot b,\\\frac{\partial r_2}{\partial d}&amp;=\frac{\partial r_2}{\partial g}=-q\cdot b,\\\frac{\partial r_2}{\partial h_1}&amp;=0,\qquad \frac{\partial r_2}{\partial h_2}=-n.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*SEhr4KsIhzVZpCY2Hvg4Cg.png" /></figure><p>These derivative columns form a Jacobian <strong>J</strong>. It propagates parameter covariance <strong>Σₓ</strong> into railhead-position covariance:</p><figure><img alt="Equation: \Sigma_{\mathrm{rail}}\approx\Sigma_{\mathrm{line}}+J\Sigma_xJ^{\mathsf{T}}+\sigma_{\mathrm{dir}}^2AA^{\mathsf{T}}" src="https://cdn-images-1.medium.com/proxy/1*d3GvrSO5N1Dius_NXGftxQ.png" /></figure><p>The last term accounts for direction uncertainty. If <strong>r</strong> is the offset from the conductor line to a head, <strong>A = [b × r, n × r]</strong> contains the displacements due to two small rotations of the tangent. <strong>σdir</strong> is their angular standard deviation.</p><p>Using the dimensions of our cross-section and a tilt error of <strong>0.1° ≈ 0.001745 rad</strong>, the angular contribution alone gives characteristic displacements:</p><figure><img alt="Equation: \begin{aligned}\delta_1&amp;\approx\sqrt{0.622^2+0.271^2}\cdot0.001745\approx1.18\mathrm{\ mm},\\\delta_2&amp;\approx\sqrt{2.205^2+0.271^2}\cdot0.001745\approx3.88\mathrm{\ mm}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*Gj8HMJ088FW4KINOAB2OQQ.png" /></figure><p>The same angular error has more than three times the effect at the farther head. This small calculation leaves other uncertainty sources aside.</p><figure><img alt="Modelled standard deviations in two transverse directions. Angular uncertainty has a longer lever arm at the farther running rail." src="https://cdn-images-1.medium.com/proxy/1*lTTwzDg0FOV_LeemoLyxiA.png" /><figcaption>Modelled standard deviations in two transverse directions. Angular uncertainty has a longer lever arm at the farther running rail.</figcaption></figure><p>The plot has steps near 30 and 60 m because the uncertainty model imposes different floors in different range bands. The trajectory itself remains smooth there.</p><p>As distance from the nearby anchor increases, the model adds uncertainty in tilt and relative offsets. Gaps in support increase it further. The envelope test below still uses fixed geometric margins: covariance neither replaces the inclusion test nor supplies a collision probability.</p><h3>7. Stop a beautiful curve from wandering into a wall</h3><p>A smooth curve can be extended beyond the measurements and still look plausible. Before placing an envelope on it, we check how far the track is actually supported by points.</p><p>An unpleasant failure appeared when the conductor-profile search stopped: the continued track could drift towards a wall. The envelope test then honestly found wall points. The mistake happened earlier, when we decided the train would travel there.</p><p>We test extensions beyond the observed region in sections roughly <strong>2 m long in the sensor’s longitudinal coordinate</strong>. For each predicted railhead, interpolate its position and collect raw points nearby:</p><figure><img alt="Equation: \begin{aligned}| v_i-v_{\mathrm{rail}}(s_i)|&amp;\leq0.055\mathrm{\ m},\\| z_i-z_{\mathrm{rail}}(s_i)|&amp;\leq0.030\mathrm{\ m}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*xXahlxVXMQlrqQUUqQM3Xg.png" /></figure><p>In each section, <strong>both heads</strong> must have:</p><ul><li>At least three supporting points.</li><li>At least three occupied 3 cm voxels.</li><li>A longitudinal span of at least 0.5 m.</li></ul><p>Voxel indices are:</p><figure><img alt="Equation: k(p)=\left(\left\lfloor\frac{x}{0.03}\right\rfloor,\left\lfloor\frac{y}{0.03}\right\rfloor,\left\lfloor\frac{z}{0.03}\right\rfloor\right)" src="https://cdn-images-1.medium.com/proxy/1*CKG4RS1icTXAs-QBVTBGow.png" /></figure><p>Suppose the left head has 12 points, but they span only 9 cm. The count passes; the span fails. Even a hundred points on the right cannot confirm an unsupported left head.</p><p>The occupied-voxel and span tests prevent a compact cluster of nearly coincident points from supporting an entire section. The check stops at the first failed section and cuts off the distant tail; it does not jump across the gap to another convenient cluster.</p><figure><img alt="The accepted path is teal; the proposed extension is dashed. Red marks the first unsupported extension section." src="https://cdn-images-1.medium.com/proxy/1*jYK35aAV1r89SWQ3pYH5Qg.png" /><figcaption>The accepted path is teal; the proposed extension is dashed. Red marks the first unsupported extension section.</figcaption></figure><p>If the conductor rail is temporarily missing or its side is ambiguous, a usable previous path can be aligned with the current nearby pair. Any extension beyond the previously observed section still has to pass the support test.</p><p>There is a subtler case: the conductor rail is found, but the new search stops much sooner. That alone is not a reason to forget an already reconstructed path. If the observed part shortens by more than one 4 m step, we compare the saved path with the fresh nearby pair and the overlap between the two estimates. When they agree, we retain the previous tail and request a new calculation. When they conflict, we keep only the nearby region. The original geometry is allowed to age for at most five seconds; reusing it does not reset that clock.</p><p>We compare observed length. Adding 20 m of prediction to a short curve does not make it an equally well-observed path.</p><p>In this episode, the original path ends about <strong>109.33 m ahead</strong>, while the proposed continuation reaches <strong>129.31 m</strong>. In the very first added section, <strong>109.33–111.43 m</strong>, neither predicted head has any points in its allowed band.</p><p>The entire extension is rejected. Only the supported section reaches the envelope check. A tidy continuation is not enough reason to inspect farther ahead.</p><h3>8. Build the envelope and test each point</h3><p>Back to the rectangle. We now know where to put it, how to rotate it and how far it can go. After all the preceding work, testing the points inside it is fairly compact.</p><p>Split the path into short segments. Let <strong>a</strong> and <strong>b</strong> be the midpoints of railhead pairs in adjacent sections. The segment direction and length are:</p><figure><img alt="Equation: f=\frac{b-a}{\Vert b-a\Vert},\qquad L=\Vert b-a\Vert" src="https://cdn-images-1.medium.com/proxy/1*15AMhy5DVVTzpVICJtAdpA.png" /></figure><p>Let <strong>vpair</strong> be the vector from the left head to the right. Remove its longitudinal component and normalise:</p><figure><img alt="Equation: \begin{aligned}e&amp;=\frac{v_{\mathrm{pair}}-(v_{\mathrm{pair}}\cdot f)f}{\Vert v_{\mathrm{pair}}-(v_{\mathrm{pair}}\cdot f)f\Vert},\\n&amp;=f\times e.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*h2zMwPo_J9EZE99575G3Qg.png" /></figure><p>Choose the sign of <strong>n</strong> so it points upwards. A test point <strong>p</strong> has local coordinates:</p><figure><img alt="Equation: \begin{aligned}\ell&amp;=(p-a)\cdot f,\\u&amp;=(p-a)\cdot e,\qquad h=(p-a)\cdot n.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*b9JYNHbbnWgBUXMo7oSivw.png" /></figure><p>Three dot products. The first asks whether the point lies between the segment ends; the other two locate it in the cross-section.</p><p>Our experimental envelope is <strong>2.1 m wide and 3 m high</strong>. With internal margins:</p><figure><img alt="Equation: \begin{aligned}0&amp;\leq\ell\leq L,\\| u|&amp;&lt;1.05-0.03-\varepsilon_{\mathrm{edge}},\\0.10+\varepsilon_{\mathrm{edge}}&amp;&lt;h&lt;3.00-0.03-\varepsilon_{\mathrm{edge}}.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*lUs9v5DC5TxHbHrSG6bdtg.png" /></figure><p>We exclude 10 cm at the bottom and 3 cm at the sides and top. <strong>εedge = 10⁻⁶ m</strong> is an additional numerical boundary margin. The exact transverse limits are <strong>|u| &lt; 1.019999 m</strong> and <strong>0.100001 &lt; h &lt; 2.969999 m</strong>. Points on those transverse boundaries do not count as hits.</p><figure><img alt="A cross-section near the object. Red points passed the 3D envelope-segment tests and are shown here in a common transverse projection." src="https://cdn-images-1.medium.com/proxy/1*8gUKCg95lB_w9jLABynmTQ.png" /><figcaption>A cross-section near the object. Red points passed the 3D envelope-segment tests and are shown here in a common transverse projection.</figcaption></figure><p>For a segment 1 m long:</p><figure><img alt="Local coordinates (ℓ, u, h), m | Decision; (0.4, 0.8, 1.2) | Inside; (0.4, 1.03, 1.2) | Beyond the side boundary; (0.4, 0.8, 0.06) | Below the inspection region; (1.2, 0.8, 1.2) | Beyond this segment’s end" src="https://cdn-images-1.medium.com/proxy/1*-3zzJBh04P_uaUichBDavA.png" /></figure><p>The last point may still belong to a neighbouring segment. We inspect the entire accepted path, not one rectangle.</p><p>A spatial grid with 0.5 m cells avoids comparing every point with every segment. Bounding boxes identify possible intersections; exact tests then use local coordinates.</p><p>The fresh batch contains <strong>521,978 points from three consecutive clouds</strong>. <strong>90 points</strong> fall inside the envelope. The nearest is <strong>96.956 m from the LiDAR</strong>.</p><p>Those hits are measured cloud points. Reconstructed rail lines position the envelope; they do not become obstacle points themselves.</p><h3>9. Group the hits without counting one measurement twice</h3><p>We can already recognise the square in those 90 hits. The algorithm knows nothing about its shape yet. It has to connect nearby hits and assess each group’s support.</p><p>First, divide space into 5 cm voxels. Represent each occupied voxel by the mean position of its points. Connect these representatives when they are at most 24 cm apart, and find connected components. Each component then receives its original points back. Acceptance requires at least three points and two occupied voxels.</p><p>We also account for each point’s range <strong>r</strong> from the sensor:</p><figure><img alt="Equation: \begin{aligned}w(r)&amp;=\min\left(1,\left(\frac{70}{r}\right)^2\right),\\W_{\mathrm{object}}&amp;=\sum_iw(r_i),\qquad W_{\mathrm{object}}\geq3.\end{aligned}" src="https://cdn-images-1.medium.com/proxy/1*YHi3yg7gfIO7SvbQ5wahLw.png" /></figure><p>Up to 70 m, a point contributes one. At 100 m, it contributes <strong>0.49</strong>. Three points at that range give <strong>1.47</strong>; six give <strong>2.94</strong>, still below the threshold. Seven give <strong>3.43</strong> and pass this particular check.</p><figure><img alt="Equal numbers of near and far hits provide different total support." src="https://cdn-images-1.medium.com/proxy/1*jYBZB2oBbJWYVwMgKayFZw.png" /><figcaption>Equal numbers of near and far hits provide different total support.</figcaption></figure><p>At this distance, the square does not form one component. Neighbouring columns of returns are more than 24 cm apart, producing <strong>six groups of 15 points</strong>. Each has a weight sum of about <strong>7.815</strong>, so each independently exceeds three. All hits together sum to <strong>46.890</strong>, but the threshold is applied per component.</p><p>Components are then associated across batches. Final confirmation requires detections from different source batches.</p><p>This is an easy place to fool ourselves. We accumulated old clouds to reconstruct the rails. Feed old obstacle points back as new evidence, and the same handful of returns can repeatedly confirm its own existence.</p><p>Geometry history and fresh obstacle observations therefore stay separate. Measurements retain their provenance; reusing an old cloud does not create independent evidence.</p><p>After <strong>0.30 s</strong>, another non-overlapping batch produces <strong>90 hits</strong>, with the nearest at <strong>96.487 m</strong>. The tracker associates the six groups with their earlier observations and confirms each. The square is detected before its returns merge into one continuous component.</p><p>As we approach, the returns become denser. At <strong>74.98 m</strong>, <strong>324 points</strong> form one component; at <strong>61.60 m</strong>, there are <strong>495</strong>.</p><figure><img alt="Four moments while approaching the same object. Red points belong to accepted components; the panel scales are identical." src="https://cdn-images-1.medium.com/proxy/1*s43n5zXBVBt47ExVO00v7A.png" /><figcaption>Four moments while approaching the same object. Red points belong to accepted components; the panel scales are identical.</figcaption></figure><p>For the summary table, detections are also merged coarsely within a 10 m radius. Each group’s anchor stays fixed: new observations are compared with that anchor, not an ever-moving centre. Otherwise, a chain of neighbouring fragments could gradually merge half the tunnel. Separate nearby objects can still share one summary row, so the underlying observations remain available for inspection.</p><h3>A wire from above: first a point, then an object</h3><p>The large obstacle gave us a recognisable grid of 90 hits. A wire hanging from above is less generous. Most of it lies above the inspection envelope; only its lower end enters it. Hundreds of returns are not on offer here.</p><p>The algorithm needs no special “wire” class. It checks point coordinates. Let us see whether enough points survive.</p><figure><img alt="A chain of returns extends down from the ceiling near the middle of the cross-section." src="https://cdn-images-1.medium.com/proxy/1*JH-N4wHUDWscpNEK16sbbQ.png" /><figcaption>A chain of returns extends down from the ceiling near the middle of the cross-section.</figcaption></figure><p>In an early batch shown below, <strong>one point</strong> enters the envelope. That is already a geometric hit, but it cannot form an accepted component: we need at least three points in two occupied voxels.</p><p>After <strong>0.40 s</strong>, at about <strong>21.87 m</strong>, the wire’s lower end supplies <strong>six connected points</strong>. Two other isolated hits do not form components. The six wire points pass the weight threshold:</p><figure><img alt="Equation: W=6\cdot1=6\geq3" src="https://cdn-images-1.medium.com/proxy/1*7_089PFedoppRf1N-iwxQQ.png" /></figure><figure><img alt="Most of the wire is above the inspection region. Red marks six points at its lower end that passed the geometric test." src="https://cdn-images-1.medium.com/proxy/1*gVCAK_77VJ4prhPYvxqb7Q.png" /><figcaption>Most of the wire is above the inspection region. Red marks six points at its lower end that passed the geometric test.</figcaption></figure><p>Another <strong>0.40 s</strong> later, a new batch supplies <strong>nine points at 15.19 m</strong>. The tracker links this observation to the previous one and confirms the object. In the next displayed batch, at about <strong>8.54 m</strong>, there are <strong>23 points</strong>.</p><figure><img alt="The gold point does not yet form an object. Red points in subsequent batches belong to accepted components. The source-cloud batches do not overlap." src="https://cdn-images-1.medium.com/proxy/1*5hrPfHh_admPPXXwSVkO2Q.png" /><figcaption>The gold point does not yet form an object. Red points in subsequent batches belong to accepted components. The source-cloud batches do not overlap.</figcaption></figure><p>This makes the difference between an envelope hit and a confirmed object quite clear. The algorithm sees the first point, but does not yet have enough evidence to declare an obstacle. A group of returns and a fresh observation follow; the same mechanism that handled the large object confirms the wire.</p><p>You can inspect both episodes in 3D below: rotate the cloud, hide the surroundings and isolate the running-rail, conductor-rail and obstacle points. Reconstructed track lines have separate switches from the measured points. The intensity option colours the measured laser returns; it is not RGB camera colour.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fctgjebdu-the-decoder%2Fembed%2Fpreview%2FwBJxjRX%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DwBJxjRX&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fctgjebdu-the-decoder%2Fpen%2FwBJxjRX&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FwBJxjRX-512.jpg%3Fversion%3D1792868335&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/820a3d384dbf54d0a53860fb5a7c3bbe/href">https://medium.com/media/820a3d384dbf54d0a53860fb5a7c3bbe/href</a></iframe><h3>From a cloud to a confirmed object</h3><p>We began with tunnel points and an unknown region through which the train would travel. For the selected episode:</p><figure><img alt="Stage | Result; Nearby pair | Two supported railheads; Conductor profile | Right-hand side; 1,233 original returns; Profile continuation | 21 anchors; 8,742 supporting measurements; Smoothing | Spatial curve for transporting cross-sections; Reconstruction | Two running rails with uncertainty estimates; Extension check | Accepted path ends 109.33 m ahead; Envelope test | 90 hits in six components; Fresh observation after 0.30 s | Object confirmed by the tracker" src="https://cdn-images-1.medium.com/proxy/1*QuXAVZNiCJ9R9C-3q43HYg.png" /></figure><p>Here is the same episode in motion. The full track is on the left and the cross-section near the object is on the right. The first detection appears at 96.96 m; a fresh batch confirms it 0.30 s later.</p><figure><img alt="Red points are detected components. Playback pauses at the first detection and confirmation; the recording time appears at the top right." src="https://cdn-images-1.medium.com/proxy/1*E8uGWHjHTpwW8KO9qhOWaQ.gif" /><figcaption>Red points are detected components. Playback pauses at the first detection and confirmation; the recording time appears at the top right.</figcaption></figure><p>The original hackathon run detected all six obstacles identified in the visual annotation of the test recording.</p><h3>What we ended up with</h3><p>The final “is this point inside?” test took only a few inequalities. Most of the work went into placing the test region correctly: finding the nearby heads, following the conductor profile, aligning observations and reconstructing the running rails through bends. Without that, even a perfect inclusion test would search for obstacles in the wrong place.</p><p>The whole chain runs on the CPU. Python connects the stages, computational sections are implemented in C++ through pybind11, and parallel searches use OpenMP. The application can load a recording or receive a live point-cloud stream through ROS 2. The interface can open a particular detection and show the points that produced it.</p><p>What I value most is being able to work backwards from a detection. Here are the points inside the envelope. Here is the track segment that positioned it. Here are the rails and measurements supporting that segment. If something goes wrong, there is a concrete place to begin investigating.</p><p>“Find something that should not be in the tunnel” becomes a sequence of geometric questions. First: where are the rails? Then: where will the train go? Only then: what is in its way?</p><p>Adapted from <a href="https://habr.com/ru/articles/1098160/">my Russian article on Habr</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b756c2f93697" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To Train or to Filter? Removing Road Shadows Without Neural Networks]]></title>
            <link>https://medium.com/@HeinrichWirth/to-train-or-to-filter-removing-road-shadows-without-neural-networks-4ff287807502?source=rss-5b1baaab6189------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ff287807502</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Heinrich]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 18:28:46 GMT</pubDate>
            <atom:updated>2026-10-24T18:28:46.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>One real road image, six transformations, and a CPU pipeline built from local statistics, filters and constraints</h3><figure><img alt="To train or to filter? This time, filters. Original road image, correction field, and result." src="https://cdn-images-1.medium.com/proxy/1*LA3leWRc8Agbzrs43Z8-HQ.png" /></figure><p>For this task, I chose to filter.</p><p>Another road-inspection problem, another reason to spend far too long looking at asphalt. This time, the trouble was shadows in images from a line-scan camera.</p><p>We needed to find cracks and repair patches. Half the road was dark, the edge of a shadow introduced a contour of its own, and a white road marking managed to sit in both sunlight and shade. All of that would eventually become the defect detector’s problem.</p><p>It is tempting to turn up the brightness and move on. Unfortunately, noise and grain turn up with it. Add local contrast, and you may emphasise the very shadow boundary you wanted to remove. The road marking joins in too: white paint is remarkably good at making asphalt statistics less useful.</p><p>I ended up with a pipeline that corrects camera artefacts, estimates illumination, limits contrast changes and treats road markings separately. It runs on the CPU. Gaussian filters, local statistics, morphology, and a little patience with 8-bit arithmetic.</p><p>Here is the result. Then we will work through how it gets there.</p><figure><img alt="Original shadowed road and the processed result." src="https://cdn-images-1.medium.com/proxy/1*gVlVFZAI5Ynbl1zzYBqhLQ.png" /></figure><h3>Why I did not use a neural network</h3><p>I tried pretrained models. On these road images, their results were not good enough to let me run a folder through a model and call the job done. Adapting a model to this camera and these conditions would have meant a separate data and training project.</p><p>There was also a less pleasant possibility: removing the thing we had photographed the road to find. I was particularly wary of generative restoration. A model that reconstructs texture can smooth away a thin crack or alter the edge of a repair patch. The asphalt looks nicer, but the downstream detector has lost the evidence. A beautiful road with a missing real crack is an odd kind of success in road inspection.</p><p>And the working solution was needed quickly. A new round of annotation, fine-tuning and validation did not fit the schedule.</p><p>Classical image processing gave me a practical route: choose the strength of camera correction from the image series, use the pavement’s statistics as a reference, and make each transformation explicit enough to inspect.</p><h3>The input, the output, and one image we will keep coming back to</h3><p>The input is a sequence of monochrome, 8-bit TIFF images, either 2048 × 1024 or 1024 × 2048 pixels. That is a useful restriction. The surface type repeats, the frame geometry is known, and there is a whole series from which to collect well-lit reference areas.</p><p>The output is an image for finding cracks and repair patches. Brightness normalisation and visible changes to texture contrast are therefore part of the job.</p><p>For the walkthrough, I will use a frame with a broad transverse shadow, a strip of white paint and a rather opinionated asphalt texture. We will keep the same road all the way through.</p><figure><img alt="One road image with a fixed crop around the shadow boundary and road marking." src="https://cdn-images-1.medium.com/proxy/1*iprwPrbVWGKeo-G9CBnL9Q.png" /><figcaption>The yellow box fixes the crop used in the six main stage illustrations.</figcaption></figure><p>Each of the six main illustrations shows the full frame at the top and the same enlarged crop below. The yellow box follows one shadow boundary and one road marking. All grayscale road images use the same 0–255 intensity scale.</p><p>Use Back and Next to follow the six transformations. The left image is the input to the selected stage, and the right image is its output. Stage 5 returns to the lighting base and combines the two branches. Switch to the crop to inspect small details.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fctgjebdu-the-decoder%2Fembed%2Fpreview%2FYPZjrZa%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DYPZjrZa&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fctgjebdu-the-decoder%2Fpen%2FYPZjrZa&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FYPZjrZa-512.jpg%3Fversion%3D1792822733&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4034c716fbfa622d0d69cfc379bbfff/href">https://medium.com/media/b4034c716fbfa622d0d69cfc379bbfff/href</a></iframe><p>A useful starting model is:</p><figure><img alt="Equation: I(x,y)\approx R(x,y)L(x,y)+n(x,y)" src="https://cdn-images-1.medium.com/proxy/1*e-buAJ3iUZK-hp5dnkv3LQ.png" /></figure><p>Here, R represents surface reflectance, L illumination, and n noise and whatever the simplified model leaves out. Moisture, reflections, optics and the sensor also affect the image.</p><p>Given only the observed image I, there is no unique way to separate surface and illumination. A dark pixel might belong to a shadow, a repair patch or a crack. I therefore use several sources of evidence: the spatial scale of brightness changes, neighbouring regions, statistics from well-lit frames, and marking masks.</p><figure><img alt="Pipeline dependencies: the lighting base feeds both contrast processing and the final illumination branch." src="https://cdn-images-1.medium.com/proxy/1*KYR4A6NX3Ic-U2_ut8hAKg.png" /></figure><p>The branch in this diagram matters. The second branch starts from the lighting base and later receives the processed markings. The entire contrast-enhanced image does not pass through it as though it were simply the next filter. When their inputs and targets match, the branches reuse the same calculations.</p><p>I will also distinguish three things: an <strong>image</strong>, which eventually goes to the detector; a <strong>correction field</strong>, which tells us how to change brightness; and a <strong>mask</strong>, which restricts where a change is allowed. Smoothing a correction field and blurring the asphalt itself are very different operations.</p><h3>1. Correct what the camera added</h3><p>First come stripes, differences in column sensitivity, and spatial non-uniformity. The large shadow remains at this stage. We have not reached illumination yet.</p><figure><img alt="Stage 1: camera correction, full image and fixed crop." src="https://cdn-images-1.medium.com/proxy/1*LpJbL25qmrYwnJgPuGwofQ.png" /></figure><h3>2. Bring the lighting towards a common level</h3><p>This is where the shadow itself starts to change. I choose a target intensity from the series, build a gain field, and add a local brightness correction where the surroundings provide enough support. Together, those operations produce the lighting base.</p><figure><img alt="Stage 2: illumination normalisation, full image and fixed crop." src="https://cdn-images-1.medium.com/proxy/1*iaQg4LErYHOkLX8IArbXkg.png" /></figure><h3>3. Adjust texture without turning noise into convincing asphalt</h3><p>The lighting is flatter. Now the details may look weak. Matching local standard deviation to a reference seems like an obvious next move, until an almost uniform patch turns into a showcase for amplified noise.</p><figure><img alt="Stage 3: bounded contrast and tone processing, full image and fixed crop." src="https://cdn-images-1.medium.com/proxy/1*B3LZjci3zANFgQVBLWnzCQ.png" /></figure><h3>4. Give road markings their own treatment</h3><p>Most of the reasoning so far assumes a road surface. Now add a large white stripe that differs in both brightness and texture and happens to cross the shadow.</p><p>Treat it as ordinary asphalt and the illumination estimate starts compensating for a change of material. The paint gets darker; neighbouring asphalt receives a correction intended for something else.</p><figure><img alt="Stage 4: road-marking correction, full image and fixed crop." src="https://cdn-images-1.medium.com/proxy/1*owQI9OdlhtdOuQkw7iNNnw.png" /></figure><p>This is a local correction. Most of the asphalt should stay as it was, so the enlarged crop around the white stripe is the useful comparison.</p><h3>5. Combine the branches</h3><p>Here is the point where it is easy to lose track of the diagram. I return to the lighting base from stage 2, reduce local overcorrection, apply tone processing, and blend in the markings from stage 4. The complete marking-processed image is not fed through the illumination branch.</p><figure><img alt="Stage 5: lighting base and processed markings feed the combined result." src="https://cdn-images-1.medium.com/proxy/1*a6RmtG-mwqMYCUgEEJyclA.png" /></figure><h3>6. Reconcile the remaining boundary</h3><p>The main intensity difference is much smaller, but the boundary can still leave a trace. The last local adjustment matches brightness and texture to the valid surroundings.</p><figure><img alt="Stage 6: residual boundary matching, full image and fixed crop." src="https://cdn-images-1.medium.com/proxy/1*M4daENVMokkDCWjOYQLbEw.png" /></figure><p>The effect is concentrated around the remaining transition. It refines the combined result rather than brightening the whole road once again.</p><h3>The result, and a softer shadow</h3><p>Back to the first frame. The broad transverse shadow has been suppressed, although its trace is still visible in the texture in places. The enlarged crop shows why this is more than adding a brightness constant.</p><figure><img alt="The first road image in six states from the original to the final result." src="https://cdn-images-1.medium.com/proxy/1*zU35C2DLMHy9eyVn34eO7Q.png" /></figure><p>The shadow remains through camera correction. The lighting base reduces the broad intensity difference, and contrast processing makes the small-scale surface texture easier to see. Here is the same crop at four points along the way:</p><figure><img alt="The fixed crop in four image states." src="https://cdn-images-1.medium.com/proxy/1*FofrCOrMNcREeUUZohRtoA.png" /></figure><p>Contrast has changed too. A newly visible dark line is not automatically a crack; interpreting defects belongs to the next algorithm.</p><p>Now consider a broad shadow with a softer transition and no road marking. That lets us look at illumination and texture without white paint joining the discussion.</p><figure><img alt="Six image states for a broad shadow with a soft transition." src="https://cdn-images-1.medium.com/proxy/1*Dxt9gBJUZtk0um4TT_T53g.png" /><figcaption>There is no white paint in this frame. The local lighting correction is enabled.</figcaption></figure><p>The first two panels still contain a clear dark band. Brightness normalisation reduces the difference; contrast processing makes the fine texture more visible; the final adjustment reduces the remaining boundary trace. Local brightness correction is enabled in this example too. The fourth and fifth panels show connected branches, not consecutive filters applied to the entire same image.</p><figure><img alt="The same soft shadow boundary before and after processing." src="https://cdn-images-1.medium.com/proxy/1*v8lnAx8CJ3tzDPFhQIaHiA.png" /></figure><p>The dark region no longer hides the texture as strongly. The two sides still look somewhat different. Equalising illumination does not make every piece of asphalt identical.</p><h3>Two masks, two different jobs</h3><figure><img alt="Marking masks and boundary-correction strength for the two road frames." src="https://cdn-images-1.medium.com/proxy/1*fxBif0AN9U3sEpfHudLYSA.png" /></figure><p>The marking mask on the left sets a lower brightness bound at the end of processing. The map on the right controls the strength of residual-boundary matching. The second frame contains no white paint, so its marking mask is empty, while its correction map follows the soft shadow boundary.</p><p>A dark interior in the correction map is expected: broad illumination normalisation happened earlier. This map responds to residual transitions, not to every pixel inside the shadow. The masks are not complements. Boundary matching excludes protected regions and pixels already brightened by the marking stage; the full marking floor is applied afterwards.</p><h3>Full-resolution images</h3><p>For a closer look, each state is available separately:</p><p><strong>Original:</strong> <a href="https://habrastorage.org/webt/1d/b9/af/1db9af6489630d7f211be06d38ac9485.png">transverse shadow</a> · <a href="https://habrastorage.org/webt/56/cb/0d/56cb0d2f8d23fc55ddad19624c159393.png">soft shadow</a>.</p><p><strong>Camera correction:</strong> <a href="https://habrastorage.org/webt/48/bf/be/48bfbe2a366c5fad66c8964b8d703f1b.png">transverse shadow</a> · <a href="https://habrastorage.org/webt/71/77/4c/71774cfc283b6bab044a531e7ff3ec98.png">soft shadow</a>.</p><p><strong>Lighting base:</strong> <a href="https://habrastorage.org/webt/8d/ad/c2/8dadc2ce95a434e3a70eea154825e0f0.png">transverse shadow</a> · <a href="https://habrastorage.org/webt/0b/bb/ce/0bbbce4cdd41d8c94918c6465e784214.png">soft shadow</a>.</p><p><strong>Contrast, tone and markings:</strong> <a href="https://habrastorage.org/webt/f9/b8/36/f9b836bb430b5e37837d3e900ac4fd4b.png">transverse shadow</a> · <a href="https://habrastorage.org/webt/2c/b9/f2/2cb9f203e0ea9fee4d31607504af479e.png">soft shadow</a>.</p><p><strong>Combined branches:</strong> <a href="https://habrastorage.org/webt/68/f5/22/68f522e3804dcaee66d2c2edfb6c7122.png">transverse shadow</a> · <a href="https://habrastorage.org/webt/2d/e4/b2/2de4b21bcee67c163f0b068272c478ee.png">soft shadow</a>.</p><p><strong>Final result:</strong> <a href="https://habrastorage.org/webt/65/85/ea/6585ea992ee04df2f609f8ca4d56a793.png">transverse shadow</a> · <a href="https://habrastorage.org/webt/53/30/df/5330df47f0e082a92cfd12ca553d9c7b.png">soft shadow</a>.</p><h3>Inside the six transformations</h3><p>The images above show the main changes. Now let’s open each stage and follow the calculations on that same frame: first the camera, then illumination, contrast, markings, branch combination and the final boundary correction.</p><h3>Camera correction and reference selection</h3><p>If I estimate illumination immediately, sensor artefacts become part of that estimate. The algorithm has no reason to know which stripe came from the scene and which came from the camera.</p><p>The camera correction uses predefined profiles for additive column offsets, sensitivity differences and spatial non-uniformity. The strength of the stripe correction is selected automatically for the current series. Before restoring the overall brightness level, its column-wise part is:</p><figure><img alt="Equation: I_1(x,y)=\frac{I_0(x,y)-s\,a(x)}{\max(1+s\,k(x),\,0.5)}" src="https://cdn-images-1.medium.com/proxy/1*Gj9pa81ESnxj0XCxnB4zpA.png" /></figure><p>I₀ is the input image and I₁ the stripe-corrected image. The profile a is an additive intensity offset; k is the relative deviation of column sensitivity from one; s is a correction strength between zero and one. The lower bound of 0.5 on the denominator limits amplification. The median level of valid pixels is then restored, values are clipped and rounded, and spatial non-uniformity is compensated.</p><figure><img alt="Camera correction. Change in intensity, DN." src="https://cdn-images-1.medium.com/proxy/1*ujy-uonOnuqgq3K8FLedgg.png" /></figure><p>I choose s from a small set of values using reasonably uniform frames. The improvement must hold across different subsets. If it does not, the stripe correction is disabled. Having a correction available is not a reason to apply it at full strength.</p><p>One distinction is easy to miss: well-lit reference frames are selected using the original input, but their photometric statistics are calculated after camera correction. The selection criterion stays tied to the input while camera artefacts are kept out of the target statistics.</p><p>Selection uses a reduced-resolution image and windows at several scales. I take the 20th percentile in each window, a high percentile across windows, and the median across scales. The aim is to find sufficiently bright areas without allowing one white pixel to decide the fate of an entire frame.</p><h3>Illumination fields and local support</h3><h3>A target from the data</h3><p>Hard-coding a pleasant shade of grey would be convenient. The next recording might disagree.</p><p>Instead, I use well-lit reference frames from the same series. After excluding markings and invalid pixels, I collect statistics in 8 × 8 cells, aggregate them across frames and smooth the field in logarithmic space. The illumination branch derives one spatially constant target from these reference areas. A separate target is calculated for the estimate based on pre-smoothed images.</p><p>This series contains 128 frames, of which 102 were selected as references. The two target levels are approximately 75.05 and 75.30 DN. DN stands for digital number: the encoded intensity of an 8-bit pixel ranges from 0 to 255.</p><p>A constant target does not mean a constant correction. A dark cell must be brightened; a cell already brighter than the target may be darkened.</p><figure><img alt="A shared target of 75.05 DN produces gains of 4.46 and 0.84 in two example cells." src="https://cdn-images-1.medium.com/proxy/1*l2uL4I0-UCsbq467tgPjjg.png" /></figure><p>If the series has no suitable bright reference frames, the illumination stage stops with an error. It needs a reference that the data actually supports. Only statistics are borrowed from neighbouring frames: no pieces of “good asphalt” are copied between images.</p><h3>From a mean intensity to a gain field</h3><p>Let M be the current mean intensity on the cell grid and T the target. The basic correction is:</p><figure><img alt="Equation: g=\ln\!\left(\frac{\max(T,2)}{\max(M,2)}\right); I^\prime\approx I\,\exp(\widetilde{g})" src="https://cdn-images-1.medium.com/proxy/1*gKQXHEZUmTARzdvPd17-wg.png" /></figure><p>The tilde denotes interpolation of the logarithmic field to full image resolution. Taking a logarithm turns multiplicative brightness changes into additions and subtractions. The floor of two prevents division by zero and limits the gain in nearly black cells. The implementation also compresses highlights smoothly before clipping and rounding the result.</p><figure><img alt="Apply the first illumination field. Logarithmic illumination gain." src="https://cdn-images-1.medium.com/proxy/1*I1X3asx1tR1wr0jmVTXPOw.png" /></figure><p>The local mean mixes illumination, texture and changes of material. A sharp shadow edge is especially awkward: the same window contains two areas that need different corrections.</p><p>I therefore construct two estimates. In A, the field is estimated from the original camera-corrected image and applied to that image. In B, the field is estimated from a pre-smoothed image, but still applied to the original image. B retains the original texture; only the illumination estimate sees the smoothed version.</p><figure><img alt="Compare two illumination estimates. Difference between estimates, DN." src="https://cdn-images-1.medium.com/proxy/1*4xS5fSb82zO8ZHch2quKtw.png" /></figure><p>The difference A − B highlights places where the result is sensitive to the estimation scale. Its positive part identifies candidates for extra local correction. For a reference, I look for surrounding pixels where the smoothed absolute difference is small, excluding paint and invalid pixels.</p><h3>How much surrounding evidence is enough?</h3><p>The reference intensity is a normalised convolution, followed by a support check:</p><figure><img alt="Equation: R_{\rm ref}=\frac{G_\sigma(mA)}{\max(G_\sigma(m),\varepsilon)}; N_{\rm eff}=\frac{(\sum_i w_i)^2}{\sum_i w_i^2}" src="https://cdn-images-1.medium.com/proxy/1*Qus5uEOlXSwWlL6WKps0YA.png" /></figure><p>Gσ is Gaussian smoothing, m is the valid-reference mask, and ε is a small positive denominator floor. Dividing by the smoothed mask matters: otherwise excluded pixels would behave like black pixels and pull the average down.</p><figure><img alt="Estimate brightness from the valid surroundings. Reference intensity, DN." src="https://cdn-images-1.medium.com/proxy/1*iT_lvwcy7dpN2hqu216mlA.png" /></figure><p>The second expression is the effective sample size. Here, wᵢ is the Gaussian weight of a valid reference pixel; excluded pixels have zero weight. The expression describes how concentrated those weights are; it does not make neighbouring pixels independent. A few valid pixels at the edge of a large window should not count as a well-supported reference.</p><p>A useful shortcut follows from wᵢ² ≤ wmaxwᵢ: the effective sample size is at least Σwᵢ/wmax. If that lower bound already passes the support requirement, the convolution of squared weights can be skipped.</p><figure><img alt="Check the strength of surrounding support. Effective weighted sample size." src="https://cdn-images-1.medium.com/proxy/1*7-smP5CPErO0cgEldKspQQ.png" /></figure><p>Where support is sufficient, the positive correction comes from the difference between the reference level and a local low-frequency estimate of A. Elsewhere, a bounded component-based fallback is used. The addition is limited by the remaining headroom to 248.49 DN.</p><figure><img alt="Apply the local brightness correction. Permitted brightness addition, DN." src="https://cdn-images-1.medium.com/proxy/1*TSLpLI8l2N9C34IHQCDXUQ.png" /></figure><p>I also keep a logarithmic map of the applied brightening. Later, after contrast correction, it will let me smooth the transitions in the correction itself.</p><p>This extra local correction has its own frame-selection criterion. Frames that do not pass it retain the ordinary brightness normalisation. Both walkthrough frames pass this criterion.</p><h3>Contrast limits, mean projection and tone mapping</h3><p>I compare texture statistics at several scales in logarithmic standard-deviation space. A positive difference Δ means the reference calls for more contrast. That request is reduced according to its uncertainty:</p><figure><img alt="Equation: \rho=\mathrm{clip}_{[0,1]}\!\left(1-\frac{U}{\Delta^2}\right)\quad (\Delta&gt;0); \rho=0\quad (\Delta\leq0); h=\max(\Delta,0)\,\rho\,(1-p)" src="https://cdn-images-1.medium.com/proxy/1*OcHayHoRoDKcIMf9GplWHw.png" /></figure><p>U combines the uncertainties of the current and reference statistics; p is the protected-pixel fraction; h is the logarithm of the allowed gain. The clip operator limits a value to the indicated interval. Missing or invalid statistics disable the request as well.</p><p>If the difference is small relative to its uncertainty, the request for extra contrast shrinks, possibly to zero. A zero request means a multiplier of one: no extra contrast is added. Protected areas also reduce the request.</p><figure><img alt="Reduce an uncertain contrast request. Retained fraction of the request." src="https://cdn-images-1.medium.com/proxy/1*t_xTL4pU2BKcVXL5kz0qvQ.png" /></figure><p>I then cap the gain using the texture already present in the camera-corrected image and the lighting base:</p><figure><img alt="Equation: S=\min\left(V_8(I_{\rm camera}),V_8(I_{\rm base})\right); S^\prime=\max(S-0.25,0); k_{\max}=1+\sqrt{S^\prime/0.25}" src="https://cdn-images-1.medium.com/proxy/1*Pr-6vidDTDx1P5w-tfzTnw.png" /></figure><p>V₈ is the variance within an 8 × 8 cell. I take the smaller variance, subtract a small threshold and derive the maximum gain. The limit is interpolated to full resolution; protected pixels receive a gain of one.</p><p>The 0.25 DN² threshold is the square of the maximum rounding error of half an intensity unit. It is an engineering threshold, not a measured camera-noise variance.</p><figure><img alt="Limit the detail gain. Permitted detail gain." src="https://cdn-images-1.medium.com/proxy/1*YvvAKbFZK0aG7kXeK0GSSQ.png" /></figure><h3>Keep the cell means under control</h3><p>Contrast changes can quietly change mean brightness too. I first subtract the local mean of the added correction. Then I project the candidate image onto three constraints: keep each cell’s mean, keep protected pixels unchanged, and keep the remaining values within 0–255.</p><figure><img alt="Apply the gain to fine detail. Change in intensity, DN." src="https://cdn-images-1.medium.com/proxy/1*_sumR6XVLvGQiMj8V-MIqg.png" /></figure><figure><img alt="Equation: \sum_{i\in F}\mathrm{clip}_{[0,255]}(c_i-s)+\sum_{i\in P}b_i=Q" src="https://cdn-images-1.medium.com/proxy/1*JaxXhXlzHfHqx0TerHpjBA.png" /></figure><p>F and P are the free and protected pixels in a cell. The cᵢ values are the contrast-adjusted candidates; bᵢ are the protected pixels’ values before contrast adjustment. Q is the intensity sum of that cell in the lighting base. The unknown s is a common shift for the free pixels. Mean preservation applies before the final integer rounding; rounding may change the mean slightly.</p><figure><img alt="Restore the cell means within the allowed range. Change in intensity, DN." src="https://cdn-images-1.medium.com/proxy/1*H07JHJQgakXILnIME2Aj4A.png" /></figure><p>Now the saved brightening map returns. Call it H, with a smoothed version H̃. After the projection, I apply:</p><figure><img alt="Equation: I_{\rm smooth}=I_{\rm contrast}\,\exp(\widetilde{H}-H)" src="https://cdn-images-1.medium.com/proxy/1*VEzl0k7Ac6IZLPSwVs5hbQ.png" /></figure><figure><img alt="Smooth the correction field. Brightness multiplier." src="https://cdn-images-1.medium.com/proxy/1*yAEq7MCbj1WlGT3zL8BAoA.png" /></figure><p>The multiplier changes the smoothness of the applied correction. The asphalt texture itself is not passed through this Gaussian blur. The product is clipped and rounded. This happens after the mean projection and before tone mapping.</p><h3>Map tones, then limit bright detail</h3><p>I divide the intensity range into 13 bands using quantile thresholds and assign a multiplier to each band. For an 8-bit image, the resulting mapping fits in a 256-entry lookup table.</p><p>The ordinary and gain-limited contrast variants share the same thresholds. Otherwise, a small local change could shift the tone partition of the whole frame.</p><figure><img alt="Apply the tone mapping. Tone-band index." src="https://cdn-images-1.medium.com/proxy/1*8bUGt8K6mf_CHwaZL6whbQ.png" /></figure><p>After tone mapping, I limit positive detail: local excursions above the background. Their relative amplitude is compared with reference statistics and reduced where necessary. This step can weaken a bright detail; it does not amplify it.</p><figure><img alt="Limit bright detail. Retained fraction of bright detail." src="https://cdn-images-1.medium.com/proxy/1*AQ8-sEs5Cra0u5JhAaAaww.png" /></figure><p>There is more bookkeeping here than in “multiply detail by a gain”. In return, each operation has a specific set of things it is allowed to change.</p><h3>Marking masks, boundary evidence and brightness budgets</h3><p>The marking mask uses intensity, positive deviations from the local background, the absolute Laplacian, GrabCut and connected components. Further checks use the series statistics, region properties and boundaries. A candidate should be brighter than its surroundings in the input, have a sufficiently distinct boundary, and have suitable internal texture. One clue alone is not enough.</p><figure><img alt="Find the road markings. Road-marking mask." src="https://cdn-images-1.medium.com/proxy/1*b_4dPByV5E2MWVqtCm-XsA.png" /></figure><h3>Is there a separate step at the boundary?</h3><p>This part is more interesting than a brightness threshold.</p><p>I construct normals along a region’s boundary and measure the intensity change from outside to inside. Then I subtract the continuation of the local gradients on either side.</p><p>Imagine asphalt that gets gradually brighter. Neighbouring pixels differ, but there is no separate material boundary. Removing the continuation of the smooth gradient should remove that response.</p><p>Contour pixels are dependent, so I first aggregate responses into 6 × 6 blocks on a reduced-resolution image. The block means are used to compare two models: no extra step, or an additional positive step.</p><figure><img alt="Equation: E_0=\sum_i r_i^2,\qquad E_1=\sum_i(r_i-\overline{r})^2; B=n\ln(E_0/E_1); n&gt;1,\quad\overline{r}&gt;0,\quad B&gt;\ln n" src="https://cdn-images-1.medium.com/proxy/1*WaeIhPNg8Kqd7UO2G-0FFQ.png" /></figure><p>The rᵢ values are the residual boundary responses, r̄ their mean, and n the number of blocks. E₀ and E₁ are the two residual sums of squares. Small denominator floors handle zero residuals. The BIC-like penalty asks whether adding the step improves the fit enough to justify it.</p><p>This is a model-selection heuristic, not a probability that a region is paint. It supports the acceptance of additional regions rather than replacing the other mask checks.</p><figure><img alt="Candidate region and its 30 measured boundary-block responses." src="https://cdn-images-1.medium.com/proxy/1*dPgK7wfZzcPCCkz1nG0msw.png" /><figcaption>A positive step remains after subtracting the smooth local gradient.</figcaption></figure><p>For this boundary, 30 blocks give a mean excess response of 0.541. The improvement B = 55.065 exceeds ln(30) = 3.401, so the extra positive step passes the test.</p><h3>A brightness budget, not a bucket of white paint</h3><p>The permitted brightening comes from the surroundings, excluding the marking itself. The search region expands until it contains enough supporting pixels. Component reliability further reduces the allowed addition: weak evidence means less brightening.</p><figure><img alt="Brighten paint within its budget. Permitted addition, DN." src="https://cdn-images-1.medium.com/proxy/1*V2Oe9HOkAcJK_6NJRPOmgg.png" /></figure><figure><img alt="Reduce the addition when evidence is weak. Component reliability." src="https://cdn-images-1.medium.com/proxy/1*RSYsCM1BaYWIgOFMp7GFfg.png" /></figure><p>The reliability check reduces the permitted addition. Some pixels therefore become darker between these two steps, but the correction reduces the brightening rather than darkening the original input.</p><p>The result is stored separately. We will use it when combining the branches and once more when protecting markings at the very end.</p><h3>Statistical weights and branch combination</h3><h3>Find unusual local behaviour</h3><p>Even with the earlier limits, local normalisation can overcorrect an unusual surface region. This branch uses a reference feature bank collected from 24 frames. It is separate from the 102 well-lit frames used to choose this series’ target brightness.</p><p>On the camera-corrected image, I calculate local quantiles in 16 × 16 windows with a stride of four pixels, together with the brightness and grain of a surrounding ring. Two main features are:</p><figure><img alt="Equation: \tau=\ln\!\left[1+\frac{\max(q_{50}-q_{10},0)}{\max(q_{90}-q_{50},0)+1}\right]; d=\mathrm{asinh}\!\left(\frac{\mu-q_{50}}{1.5\nu+1}\right)" src="https://cdn-images-1.medium.com/proxy/1*9NoNs-4NT9astSNrTcPdHg.png" /></figure><p>The q values are the 10th, 50th and 90th percentiles. The ring is a 65 × 65 window with the central 33 × 33 region excluded. Its mean intensity is μ. Its grain ν is the mean absolute difference between the image and a Gaussian-smoothed version with σ = 2. The inverse hyperbolic sine compresses large values.</p><p>The first feature compares the spread below and above the median. It grows when the dark side is more spread out. The second measures how dark the centre is relative to its surroundings, scaled by their grain. Both features come from the camera-corrected image, while the image we will adjust is the lighting base.</p><p>A single threshold for all asphalt would be crude. I therefore also use log background intensity and relative grain as context. Regions are grouped, and expected statistics combine nearby reference-bank examples with a local estimate. Less local evidence means more reliance on the bank.</p><figure><img alt="Measure the dark-side spread. Quantile asymmetry." src="https://cdn-images-1.medium.com/proxy/1*4S0K4lJBKFHId6xBrHgdow.png" /></figure><figure><img alt="Measure darkness relative to the surroundings. Relative darkness." src="https://cdn-images-1.medium.com/proxy/1*6v7M9EPX-_5vxLvuxHkRqg.png" /></figure><p>The resulting non-negative anomaly score z becomes a bounded correction weight:</p><figure><img alt="Equation: w=\frac{z}{z+1},\qquad z\geq0" src="https://cdn-images-1.medium.com/proxy/1*y8XqtByN6a_D7uohN61X8A.png" /></figure><p>A number between zero and one looks familiar, but w is not a shadow probability. It controls how strongly the gain field is modified.</p><figure><img alt="Turn unusual statistics into a correction weight. Correction weight." src="https://cdn-images-1.medium.com/proxy/1*-PJo0IE6t7uIko67eO_1Yg.png" /></figure><h3>Apply morphology to the correction field</h3><p>Let b be the lighting base and I the camera-corrected image:</p><figure><img alt="Equation: g=\ln\!\left(\frac{\max(b,1)}{\max(I,1)}\right),\qquad g_o=g\circ E; \delta=\max(g-g_o,0)\,w; b^\prime=b\exp(-\delta)" src="https://cdn-images-1.medium.com/proxy/1*xDRlrKtHR54Z2FkZ_gbK1Q.png" /></figure><p>The circle denotes morphological opening with a 23 × 23 elliptical element E. It provides a smoother baseline for the gain field. Positive local peaks above that baseline are reduced according to w. Protected regions are excluded from this adjustment.</p><figure><img alt="Suppress peaks in the illumination gain. Removed logarithmic gain." src="https://cdn-images-1.medium.com/proxy/1*PZPdEjn66l1J5l73FIp3lw.png" /></figure><p>The morphology acts on the gain field. It does not directly open the asphalt image and its fine details.</p><p>I then smooth the correction field, apply tone mapping with the same thresholds, and limit positive detail. The reference-driven contrast boost from stage 3 is not applied again here: it could bring back some of what this branch just suppressed.</p><figure><img alt="Smooth the correction in the lighting branch. Brightness multiplier." src="https://cdn-images-1.medium.com/proxy/1*uIUGpY1JuGPUvsjOB2423Q.png" /></figure><figure><img alt="Reuse the tone mapping in the lighting branch. Change in intensity, DN." src="https://cdn-images-1.medium.com/proxy/1*ioFJAr08hikDJJhYCxUlrA.png" /></figure><figure><img alt="Limit bright detail in the lighting branch. Retained fraction of bright detail." src="https://cdn-images-1.medium.com/proxy/1*y5vTqxJyJqFJ3MYhZMjhuA.png" /></figure><p>Finally, I blend in the marking result. The weight p is one where the marking stage brightened its input, with a smooth transition nearby. With C for the illumination-branch result and M for the processed markings:</p><figure><img alt="Equation: J=\mathrm{round}\!\left(C(1-p)+Mp\right)" src="https://cdn-images-1.medium.com/proxy/1*oJbhfJy3Yf9R1dwES1ikgw.png" /></figure><p>The result J is rounded to the nearest integer. The reference bank supplies pavement statistics; it does not supply replacement image texture.</p><figure><img alt="Blend the processed markings back in. Marking blend weight." src="https://cdn-images-1.medium.com/proxy/1*areWf6UB29CXLfSQvezqKw.png" /></figure><h3>Residual-boundary matching and final protection</h3><p>I take the signed difference between two brightness transformations of a smoothed frame. The outer smoothing uses σ = 16 pixels; the second estimate also includes internal smoothing.</p><p>The correction ramps up between responses of 4 and 12 DN:</p><figure><img alt="Equation: t=\mathrm{clip}_{[0,1]}\!\left(\frac{\max(r,0)-4}{8}\right); \alpha=t^2(3-2t)" src="https://cdn-images-1.medium.com/proxy/1*lctDomI0XfD4ZWfjD3hZ5A.png" /></figure><p>Here, r is the signed difference between the two brightness estimates, and t is its rescaled and clipped value. The smoothstep function avoids an abrupt switch at a threshold. Protected pixels have α set to zero.</p><figure><img alt="Find the remaining boundary. Boundary correction strength." src="https://cdn-images-1.medium.com/proxy/1*ykChNct67hJ4w0gJdQcmXA.png" /></figure><p>Reference brightness and grain come from the valid surroundings with σ = 48. This broad reference is evaluated on a half-resolution grid. Sparse support reduces the correction further. The texture multiplier is limited to 0.65–1.5 and the brightness shift to −80…80 DN.</p><figure><img alt="Account for surrounding support. Effective correction strength." src="https://cdn-images-1.medium.com/proxy/1*NOOgunzNk3vxmSKevPYWPw.png" /></figure><p>Writing the effective strength, after accounting for support, as β gives:</p><figure><img alt="Equation: J^\prime=J+\beta\left[\Delta\mu+(k-1)(J-\mu_l)\right]" src="https://cdn-images-1.medium.com/proxy/1*ERtf68u_EfaWVaXtOeYK5Q.png" /></figure><p>Δμ is the brightness shift and k the texture multiplier. The local background μₗ is obtained with an 11 × 11 median filter followed by Gaussian smoothing with σ = 3. After clipping and rounding, protected pixels and pixels with zero correction strength retain their previous values.</p><figure><img alt="Match brightness and texture to the surroundings. Brightness shift, DN." src="https://cdn-images-1.medium.com/proxy/1*oDZ3-sHIGZrD6ztnEPG41A.png" /></figure><p>There is one final condition on the marking mask:</p><figure><img alt="Equation: I_{\rm final}=\max(J^\prime,M)\quad\mathrm{inside\ the\ marking\ mask}; I_{\rm final}=J^\prime\quad\mathrm{elsewhere}" src="https://cdn-images-1.medium.com/proxy/1*QOrA3W4B6JwTXWBwNcs2iw.png" /></figure><p>Processed paint cannot end up darker than the marking result M. There is no instruction to force it to 255. Where the image is already bright enough, this condition changes nothing.</p><figure><img alt="Protect the processed markings from darkening. Final marking mask." src="https://cdn-images-1.medium.com/proxy/1*sAa13i2yyqUyt4AaTZjAog.png" /></figure><h3>Making the calculations work on a CPU</h3><p>Each frame needs illumination estimates, local statistics and several related corrections. Fortunately, neighbouring windows share pixels, and branches share intermediate results. Three implementation choices make use of that structure while preserving the integer output.</p><h3>The window moved. Why sort everything again?</h3><p>Local quantiles come from a 16 × 16 window histogram: 256 counters for the possible pixel intensities. Move the window four pixels and 192 of its 256 pixels are unchanged.</p><figure><img alt="A 16 by 16 window shifted by four pixels retains 192 pixels and exchanges 64." src="https://cdn-images-1.medium.com/proxy/1*ZuuSmpeLEJeM4TjRziZ-SQ.png" /></figure><p>Subtract the departing columns from the histogram, add the arriving columns, and find the quantiles from cumulative counts. The common pixels have already been counted.</p><h3>One region changed. Why recalculate the entire frame?</h3><p>The contrast stage has two related calculations: one uses the requested gain, and the other also applies the variance-based limit. Both need the 8 × 8 cell-mean projection.</p><p>The limiter changes the gain only in part of the image. The algorithm marks affected cells and repeats the projection there. Wherever the inputs match, it reuses the existing result.</p><figure><img alt="One changed gain cell and the surrounding cells that need projection." src="https://cdn-images-1.medium.com/proxy/1*xKh-wsSZqSpm6l4KGarPWA.png" /><figcaption>Interpolation expands the affected area beyond the cell where the gain first changed.</figcaption></figure><p>One changed gain cell can require nine cells to be recalculated because interpolation can affect its neighbours. The affected set is expanded by a 3 × 3 neighbourhood on the cell grid. If too many cells are affected, a full-frame pass is used.</p><h3>The pixel will be 80 anyway. Why keep refining it?</h3><p>The cell-mean projection must find a brightness shift. An approximate solution and valid bounds can sometimes establish the final integer result before the continuous solution is fully refined.</p><p>If a pixel must lie between 80.10 and 80.30, it will round to 80 throughout that interval. Between 80.45 and 80.55, it can round either way.</p><figure><img alt="An interval that always rounds to 80 and an interval crossing the 80.5 rounding boundary." src="https://cdn-images-1.medium.com/proxy/1*rFxjkCMdLrSsOOrGHsbboA.png" /></figure><p>The check covers the solution bounds and every free pixel in the cell. If all rounded outputs are determined, the result is accepted. Otherwise, the calculation falls back to 28 bisection steps. The shortcut depends on a rounding guarantee, not on a “probably close enough” tolerance.</p><h3>A few details that matter for memory</h3><p>Illumination and marking statistics share a pass over reference frames. Intermediate images stay in memory between branches, and masks are reused only when their inputs are unchanged.</p><p>The marking-brightening budget uses 64-level histograms. Those loops and some integer reductions are compiled with Numba.</p><p>Cells requiring another projection are packed into an array eight pixels high, processed together and copied back. The float32 summation order is fixed so rounding stays reproducible.</p><p>One intermediate grain estimate can stay in uint8: the absolute difference between an 8-bit pixel and its median-filtered neighbourhood is still in 0–255. That difference and the following median filter retain the integer representation. Conversion to float32 and multiplication by 1.4826 happen afterwards. The intermediate array needs one byte per element.</p><h3>Two more roads through the same pipeline</h3><figure><img alt="Two further road images before and after processing." src="https://cdn-images-1.medium.com/proxy/1*gglwoaVXqqOiZatshsbijA.png" /></figure><p>In the first example, the large illumination difference is weaker, but the vertical structure remains pronounced. The diagonal shadow in the second example is suppressed more successfully, while the white stripes look flatter.</p><p>The lighting becomes more even and the texture more visible, but some boundaries remain. How well a shadow is suppressed depends on the scene.</p><p>Full resolution: first example — <a href="https://habrastorage.org/webt/4a/7d/bf/4a7dbf21c6639efe864a90fe1362c57d.png">original</a> and <a href="https://habrastorage.org/webt/eb/27/3e/eb273e326404464accb19fbff6f9a00c.png">result</a>; second example — <a href="https://habrastorage.org/webt/ba/20/d3/ba20d33144c1b4b89d3a77da6e00bb4b.png">original</a> and <a href="https://habrastorage.org/webt/5f/fd/b2/5ffdb2597d3a05773235d5725b28d8ff.png">result</a>.</p><p>This preprocessing was sufficient for our next task: training models to find cracks and repair patches. Detection quality improved substantially compared with using the original images, although the improvement was not several-fold.</p><h3>Where this approach ends</h3><p>This pipeline is tied to a particular acquisition setup: monochrome 8-bit frames, fixed dimensions and camera-correction profiles. Another camera or a 16-bit signal would require revisiting those profiles and parameter scales.</p><p>It also needs a series with well-lit reference frames. Statistics are collected across a folder, so this is batch processing. Change the reference set, and the output for the same frame may change.</p><p>What I value about the solution is that I can take it apart. I can see where the target brightness came from, why the contrast increased, where surrounding support ran out, and which pixels a mask protected. An unsatisfactory result points to a specific calculation worth inspecting.</p><p>The neural network gets the next job: finding cracks and repair patches in the prepared images. For illumination, local statistics, filters and bounded corrections were enough.</p><p>To train or to filter? This time, the filters got the job.</p><p><em>Adapted from my </em><a href="https://habr.com/ru/articles/1097026/"><em>Russian article on Habr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ff287807502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Good Roads, Bad Data: Making Synthetic Road Defects with Nano Banana Pro]]></title>
            <link>https://medium.com/@HeinrichWirth/good-roads-bad-data-making-synthetic-road-defects-with-nano-banana-pro-215d7e2f98e6?source=rss-5b1baaab6189------2</link>
            <guid isPermaLink="false">https://medium.com/p/215d7e2f98e6</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <dc:creator><![CDATA[Heinrich]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 04:43:58 GMT</pubDate>
            <atom:updated>2026-10-24T04:55:42.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generate the mask first, add worn asphalt patches second, and keep the labels under control</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K-qGA1-VC-82MCUF.jpeg" /></figure><p>The data is rubbish, and there isn’t enough of it. Let’s generate some.</p><p>The end.</p><p>That was the short version. The slightly longer version involves road photographs, invented defects, and the discovery that “do not change anything else” is a request, not a guarantee.</p><p>I needed more data to train a model to find asphalt repair patches and potholes. We had plenty of footage of perfectly decent roads. What we lacked was enough useful, consistently labelled damage in the conditions our cameras actually saw.</p><blockquote><em>If you already have kilometres of good road on video, the obvious thing to do is make the road worse. Digitally, preferably.</em></blockquote><p>This is a practical experiment I first wrote about in February 2026. The examples below come from those trials. The accompanying <a href="https://github.com/HeinrichWirth/banana-road-synth">Python repository</a> contains the prompts and a folder-processing pipeline, including the local checks and background-preserving step described here.</p><h3>Why not just use an existing dataset?</h3><p>There are open road-damage datasets, including <a href="https://github.com/sekilab/RoadDamageDetector">RDD2022</a>. They are useful starting points. They do not automatically give you the examples you need for a particular camera, road surface and labelling task.</p><p>For context, the <a href="https://crddc2022.sekilab.global/data/">CRDDC2022 benchmark</a> focuses on longitudinal cracks, transverse cracks, alligator cracks and potholes. My problem also involved repair patches. A repaired area and a hole in the asphalt are different targets, even if both make a road look less than pristine.</p><p>Then there is the domain itself. Russian asphalt repairs sometimes feel like a separate art form. The texture, materials and shapes can look quite different from examples collected elsewhere. Change the camera and viewing angle as well, and a model that looked promising on a public dataset can become much less convincing on your own footage.</p><p>I could organise another survey, search through more recordings and draw more masks by hand. None of that sounded like the quickest way to test an idea. So I tried synthesising the missing examples on top of the real scenes we already had.</p><h3>A nice-looking image is not enough</h3><p>I started with ChatGPT’s image generation. In the examples I tried, it could produce a damaged road, but the defects did not follow the supplied mask closely enough. It also redrew parts of the scene I had wanted to keep.</p><figure><img alt="Original photograph used in the first image-generation trial." src="https://cdn-images-1.medium.com/proxy/0*yBHXNnOAQOVuwBDY.png" /><figcaption>Original photograph used in the first image-generation trial.</figcaption></figure><figure><img alt="ChatGPT output from that trial. The edits did not follow the intended mask closely enough." src="https://cdn-images-1.medium.com/proxy/0*U70SfbfPAYZCoEjC.png" /><figcaption>ChatGPT output from that trial. The edits did not follow the intended mask closely enough.</figcaption></figure><figure><img alt="The mask supplied for the edit above." src="https://cdn-images-1.medium.com/proxy/0*AJgkGUfQobMvh0HB.png" /><figcaption>The mask supplied for the edit above.</figcaption></figure><p>That is an awkward failure for a training-data pipeline. A convincing repair patch is only half the output. The mask has to describe where that patch actually is.</p><p>The off-the-shelf FLUX and Stable Diffusion setups I tried did not solve that control problem either. Those were practical trials with the configurations I had available, rather than a controlled comparison of model families.</p><p>Nano Banana Pro was the first option in that experiment that gave me results I wanted to keep. In these examples, the generated patches followed the intended regions much more closely.</p><figure><img alt="Original photograph for the Nano Banana Pro trial." src="https://cdn-images-1.medium.com/proxy/0*MavfIPzC_29LEYPb.png" /><figcaption>Original photograph for the Nano Banana Pro trial.</figcaption></figure><figure><img alt="Generated repair patches in the same scene." src="https://cdn-images-1.medium.com/proxy/0*xUlk1FeLjaOHSprE.png" /><figcaption>Generated repair patches in the same scene.</figcaption></figure><figure><img alt="Mask overlaid on the generated result to inspect placement and boundaries." src="https://cdn-images-1.medium.com/proxy/0*6o13QcQFrmrSIUTw.png" /><figcaption>Mask overlaid on the generated result to inspect placement and boundaries.</figcaption></figure><h3>First invent the label, then invent the defect</h3><p>The order matters. I do not begin by generating a damaged road and then ask somebody to annotate it. I first ask for the locations of repairs that <em>do not yet exist</em>.</p><p>Here is the mask prompt:</p><blockquote><em>Generate a binary segmentation mask of asphalt road repair patches.<br>The mask should represent realistic, randomly shaped road patches that DO NOT exist in the original image.<br>Patches must appear only on the asphalt road surface.<br>No patches on sidewalks, curbs, grass, buildings, cars, poles, or road markings.<br>Patch shapes should be irregular, organic, and varied in size, similar to real asphalt repairs.<br>The mask must be white (255) for patches and black (0) for everything else.<br>Do not modify the original image.<br>Do not add textures, colors, lighting, or shadows.<br>Output only the segmentation mask image (no text).</em></blockquote><p>In my informal checks, roughly eight out of ten masks stayed on the road rather than wandering onto a pavement, kerb or another object. That was useful enough to make the experiment worth pursuing. I still inspected the masks before keeping a pair.</p><p>The mask returned by an image model is still an image. It can contain grey pixels, and its dimensions can differ from the input photograph. The script therefore resizes it with nearest-neighbour interpolation and turns it into a binary mask:</p><pre>import numpy as np<br>from PIL import Image<br>mask = generated_mask.convert(&quot;L&quot;).resize(<br>    original.size, Image.Resampling.NEAREST<br>)<br>binary = (np.asarray(mask) &gt;= 128).astype(np.uint8) * 255<br>mask = Image.fromarray(binary)</pre><p>Here, both inputs are Pillow images. Pixels below 128 become black; the rest become white. Nearest-neighbour resizing avoids introducing new intermediate values while scaling the mask. This makes the representation unambiguous. It does not decide whether a proposed patch belongs on the road; that is what the visual check is for.</p><p>Next, I send two images: the original photograph and this binary mask. The second prompt asks for old, worn repairs rather than shiny rectangles of fresh asphalt:</p><blockquote><em>You are given two images:<br>(1) the original photo<br>(2) a binary mask where WHITE (255) indicates the exact pixels to edit and BLACK (0) indicates pixels that must remain unchanged.</em></blockquote><blockquote><em>Task: Generate realistic asphalt road repair patches ONLY where the mask is white.<br>The patches must look OLD and worn (not fresh): low-contrast, slightly blended into the existing road, almost the same color as the road.<br>Do NOT change anything outside the white mask.<br>Do NOT touch sidewalks, curbs, grass, buildings, cars, poles, or road markings.<br>No new objects, no extra shadows, no added text.<br>Output only the edited photo (no text).</em></blockquote><p>That is the core loop: propose a location, render the repair, inspect the pair. For potholes, the same two-stage idea applies with a different description of the object. The supplied script’s default prompts generate repair patches.</p><p>The mask labels the repairs we add; any pre-existing defects need their own annotations.</p><h3>“Outside the mask” needs more than a prompt</h3><p>The original experiment relied on the instruction to leave the background alone. For the accompanying script, I made that requirement explicit in code.</p><p>After bringing the generated image to the source dimensions, copy its pixels inside the mask and keep the original pixels outside it:</p><pre>generated = generated.convert(&quot;RGB&quot;)<br>if generated.size != original.size:<br>    generated = generated.resize(original.size, Image.Resampling.LANCZOS)<br>result = Image.composite(generated, original.convert(&quot;RGB&quot;), mask)<br>result.save(&quot;patches.png&quot;)</pre><p>White selects the generated image; black selects the original. Saving the result as PNG preserves those decoded RGB values outside the mask exactly. The script also keeps the uncomposited model output, so it is easy to see what the model changed.</p><p>This fixes background drift. It does not magically fix a patch that misses its mask, or a visible seam where the generated texture meets the original. The mask overlay remains useful for precisely that reason. The example images above are the original model outputs, before this extra compositing step.</p><p>The overlay itself is cheap: inside the mask, blend 65% of the image colour with 35% red. Outside it, leave the image alone. There is no need to ask another model to draw a red inspection layer.</p><h3>Can it do more than patches?</h3><p>I also needed examples of pedestrian crossings. The image model could generate those too:</p><figure><img alt="Original scene before adding a pedestrian crossing." src="https://cdn-images-1.medium.com/proxy/0*dsYpe7-ldYAPczOH.png" /><figcaption>Original scene before adding a pedestrian crossing.</figcaption></figure><figure><img alt="Generated crossing in the existing scene." src="https://cdn-images-1.medium.com/proxy/0*58ULvIirbg5ZNw5x.jpg" /><figcaption>Generated crossing in the existing scene.</figcaption></figure><p>At that point, the tempting next question was whether it could simply segment the entire road scene for me.</p><p>Well… not reliably.</p><p>I asked for a fixed palette: green for lane markings, blue for kerbs, red for pedestrian crossings, white for road signs and black for everything else.</p><figure><img alt="First scene used in the semantic-segmentation experiment." src="https://cdn-images-1.medium.com/proxy/0*kPjPiwtWTLUc-1j_.png" /><figcaption>First scene used in the semantic-segmentation experiment.</figcaption></figure><figure><img alt="Generated semantic mask for the first scene." src="https://cdn-images-1.medium.com/proxy/0*m2WnQJBKaoIVjLuW.png" /><figcaption>Generated semantic mask for the first scene.</figcaption></figure><figure><img alt="Second scene used in the semantic-segmentation experiment." src="https://cdn-images-1.medium.com/proxy/0*kq7HgMUlGi7-AbLn.png" /><figcaption>Second scene used in the semantic-segmentation experiment.</figcaption></figure><figure><img alt="Generated semantic mask for the second scene." src="https://cdn-images-1.medium.com/proxy/0*qsGbjwCNRq-BGnPi.png" /><figcaption>Generated semantic mask for the second scene.</figcaption></figure><figure><img alt="Third scene used in the semantic-segmentation experiment." src="https://cdn-images-1.medium.com/proxy/0*5wmpFZsNR7oB19of.png" /><figcaption>Third scene used in the semantic-segmentation experiment.</figcaption></figure><figure><img alt="Generated semantic mask for the third scene." src="https://cdn-images-1.medium.com/proxy/0*sKebdom7XPN379p0.png" /><figcaption>Generated semantic mask for the third scene.</figcaption></figure><p>It often picked out markings and distinguished a crossing from ordinary lane lines. It also confused kerbs, barriers, parapets and pavements, and sometimes invented road signs. Shadows caused trouble in other examples.</p><p>The script snaps each generated colour to the nearest colour in the requested RGB palette. That gives you a cleanly encoded mask. It cannot turn a hallucinated sign into a correct label.</p><p>For this job, our specialised segmentation models were the better tool. Asking a generative model to propose new patches was useful; trusting it to annotate every object in an existing scene was a different proposition.</p><h3>And while we are here, make it evening</h3><p>Sometimes the missing variation is not the object. It is the lighting. Waiting for the right time of day, then driving the same route again, is a fairly elaborate form of data augmentation.</p><p>I tried asking the model to turn a daytime scene into dusk while keeping its layout. Here is one of the results, with synthetic defects as well:</p><figure><img alt="Daytime input for the lighting experiment." src="https://cdn-images-1.medium.com/proxy/0*b6N8x5vLtEAVoxNU.png" /><figcaption>Daytime input for the lighting experiment.</figcaption></figure><figure><img alt="Generated defects and dusk lighting in the same scene." src="https://cdn-images-1.medium.com/proxy/0*XDRgJvZ8iDOyyAWT.png" /><figcaption>Generated defects and dusk lighting in the same scene.</figcaption></figure><p>This is a separate whole-scene edit, so preserving the original background pixels would defeat its purpose. The evening output also needs its own alignment check before reusing the patch mask.</p><h3>What does it actually cost?</h3><p>Using the <a href="https://ai.google.dev/gemini-api/docs/pricing">standard Nano Banana Pro image-output rate</a> of $120 per million tokens, a 1K or 2K image output uses 1,120 tokens:</p><p><strong>1,120 × $120 / 1,000,000 = $0.1344 per generated image.</strong></p><p>The basic pipeline produces two images: a mask and an edited photograph. That gives:</p><p><strong>2 × $0.1344 = $0.2688 per pair.</strong></p><p>For 500 pairs, image output alone is <strong>$134.40</strong>. My original estimate of about <strong>$150</strong> was a rough budget with some headroom, not an all-inclusive quote. Input images, text and thinking tokens, retries and rejected results add to it. A generated candidate and an accepted training pair are not necessarily the same thing.</p><p>There is another easy way to double the bill without noticing: run all the experiments for every photograph. Mask, patches, evening and semantic segmentation are <strong>four</strong> image outputs, or <strong>$0.5376 per input</strong> before the other charges. In the current script, evening and segmentation are explicit options; the default run makes only the two requests needed for patches.</p><p>The alternative also has costs: finding the right defects, collecting footage and drawing labels. For my situation, paying for several hundred synthetic candidates was a reasonable way to explore the idea. It was not proof that every labelling job should now be replaced by generation.</p><p>Reusing masks is one possible extension of this pipeline. With 30 reusable masks and 500 edited photographs, the image-output calculation becomes <strong>530 × $0.1344 = $71.232</strong>, or about <strong>$71.23</strong>. You save mask-generation calls; you still generate each edited photograph. And each reused or transformed mask must fit the road area and perspective of its new scene.</p><h3>From a few trials to a folder of images</h3><p>The <a href="https://github.com/HeinrichWirth/banana-road-synth">repository</a> has English and Russian instructions. Put the API key in an environment variable, point the script at an image folder and first run a small preview:</p><pre>python generate.py --input ./input_images --output ./outputs --limit 1 --dry-run</pre><p>That lists the input and the maximum number of generation requests without calling the API. Remove --dry-run to generate the first pair. Inspect it before removing --limit 1.</p><p>The outputs include the proposed mask, the model’s edited photograph, the composite with the original background, and the inspection overlay. Completed stages can be reused after an interrupted run. Relative folders and original file extensions are retained so that two photographs called frame.jpg do not overwrite each other.</p><p>The February experiment used the Pro preview model. The current configuration uses the stable Pro model name and requests 1K output explicitly; both the model and prompts are easy to inspect. None of the illustrations here has been replaced with a new generation.</p><h3>The useful part is the pair</h3><p>A couple of days before the original article, Waymo published its <a href="https://community.waymo.com/blog/2026/02/the-waymo-world-model-a-new-frontier-for-autonomous-driving-simulation/">world-model work based on Genie 3</a>. Their driving simulation operates at a very different scale from a two-call road-image script. Still, I liked the timing: generating useful variations of real scenes was clearly becoming more interesting than just making amusing pictures.</p><p>For this experiment, the useful output was a pair: a plausible road defect and a mask that described it. Keeping the real scene as the starting point helped preserve the camera’s viewpoint and the surrounding context. Generating the mask first gave me a handle on where the new damage should appear.</p><p>The question for training is then whether those pairs help on held-out real footage. The examples here show how I produced and inspected the candidates; they do not establish a numerical improvement in a downstream detector.</p><p>I had plenty of good roads and not enough examples of bad ones. Making the roads worse turned out to be the easy part. Making sure the labels still meant what they said was the actual engineering.</p><p><em>Adapted from my </em><a href="https://habr.com/ru/articles/993968/"><em>Russian article published on February 8, 2026</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=215d7e2f98e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ten Examples per Class: Teaching a 3D Network to Compare Point Clouds]]></title>
            <link>https://medium.com/@HeinrichWirth/ten-examples-per-class-teaching-a-3d-network-to-compare-point-clouds-1b78f612f0ce?source=rss-5b1baaab6189------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b78f612f0ce</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Heinrich]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 04:00:15 GMT</pubDate>
            <atom:updated>2026-10-24T04:57:07.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>Voxels, shared weights and triplet loss for a small LiDAR classification problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kDkpTRSXpygCfsrS.gif" /></figure><p>My <a href="https://medium.com/@HeinrichWirth/no-labels-no-sleep-finding-road-defects-with-lidar-in-44-hours-66187b014f2a">first article about LiDAR</a> had an unexpected side effect: it helped me get a job. After the hackathon, I joined Geogracom as a research engineer. The point clouds followed me.</p><p>This time, the task sounded almost reassuring. Take an object cropped from a LAS file and decide whether it is a wire, a tree or a bridge.</p><p>Three classes. Ten examples of each. That last sentence did most of the damage.</p><p>Wires were relatively easy to distinguish in our particular dataset. Trees and bridges were more troublesome: a cropped, incomplete cloud does not necessarily look like the thing you would recognise in a photograph. Sometimes I could not confidently label the object just by looking at it.</p><p>Simple statistics (means, variances, point counts and density estimates) were not separating the difficult cases well enough. I initially ruled out neural networks because there was so little data. Then I remembered face recognition: instead of learning a separate output for every identity, a network can learn which examples belong near each other.</p><p>Could the same idea work for these 3D objects? I tried a shared 3D convolutional encoder trained with triplet loss. The first obstacle was less glamorous: how do you feed clouds with different numbers of points into the same network?</p><h3>1. Turn each cloud into a fixed-size grid</h3><p>A voxel is the three-dimensional equivalent of a pixel. Divide a volume into cells and mark which ones contain measurements. If you have played Minecraft, the visual idea needs very little explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*tgG61FYbz83D70Y5.jpg" /><figcaption>A voxel is a cell in three-dimensional space.</figcaption></figure><p>For this prototype, each object becomes a binary occupancy grid. A cell is 1 if at least one point falls inside it, and 0 otherwise. Ten points in the same cell still produce one occupied cell. We keep coarse shape and discard point multiplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*lmDdnLmUfwWM0Gsb.jpg" /><figcaption>Grid resolution changes the amount of geometric detail retained.</figcaption></figure><p>The preprocessing scales each coordinate axis independently into the interval from 0 to 1. For axis j, take the minimum and maximum over all points in the current object, subtract the minimum and divide by the range. If an axis has zero range, the code below sets its normalised coordinates to zero instead of dividing by zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EXgtjO4c66sS02Y0LLp_SA.png" /></figure><p>Here G is the grid resolution along each axis. Multiplying by G and taking the floor gives the cell index. The upper bound needs clipping: a coordinate of exactly 1 would otherwise produce index G, outside an array whose last index is G − 1.</p><p>For example, take x-coordinates 0, 5 and 10 on a grid with G = 10. They become 0, 0.5 and 1, then cell indices 0, 5 and 9. The last point belongs in the last cell, not an eleventh one.</p><p>The examples use NumPy, laspy and PyTorch:</p><pre>from pathlib import Path<br>import itertools<br>import numpy as np<br>import laspy<br>import torch<br>from torch import nn<br>from torch.utils.data import Dataset, DataLoader</pre><pre>def voxel_tensor(points, grid_size=100):<br>    points = np.asarray(points, dtype=np.float64)<br>    if points.ndim != 2 or points.shape[1] != 3 or len(points) == 0:<br>        raise ValueError(&#39;Expected a non-empty N by 3 cloud&#39;)<br>    if not np.isfinite(points).all() or grid_size &lt; 8:<br>        raise ValueError(&#39;Expected finite points and a grid of at least 8&#39;)<br>    lower = points.min(axis=0)<br>    span = points.max(axis=0) - lower<br>    normalized = np.zeros_like(points)<br>    np.divide(points - lower, span, out=normalized, where=span &gt; 0)<br>    indices = np.floor(normalized * grid_size).astype(np.int64)<br>    indices = np.clip(indices, 0, grid_size - 1)<br>    grid = np.zeros((1, grid_size, grid_size, grid_size), np.float32)<br>    grid[0, indices[:, 0], indices[:, 1], indices[:, 2]] = 1<br>    return torch.from_numpy(grid)</pre><p>The returned tensor has shape (1, G, G, G). The leading 1 is the occupancy channel; a batch adds another dimension, giving (B, 1, G, G, G). For LAS input, the loader uses scaled x, y and z coordinates:</p><pre>def read_voxel(path, grid_size=100):<br>    cloud = laspy.read(path)<br>    return voxel_tensor(np.column_stack((cloud.x, cloud.y, cloud.z)), grid_size)</pre><p>There is a trade-off hidden in this short normalisation formula. Independent axis scaling removes absolute dimensions and changes aspect ratios. A long, thin object is stretched to fill the same box as a compact one. I retain that choice here because it is part of the original approach. To preserve proportions, subtract the coordinate-wise minimum and then divide all three coordinates by the largest of the three axis ranges. Use the same convention in training and prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*GYPZFBPMz3aYU2VF.png" /><figcaption>An object represented as a point cloud.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*cKmt7ZL4VnJKizRR.png" /><figcaption>The same example after voxelisation.</figcaption></figure><p>The pictures show the point cloud and its voxel representation from the original project. The cubes are useful for inspection; the network receives the occupancy array, not a triangle mesh exported for viewing.</p><h3>2. One encoder, three inputs</h3><p>A Siamese network does not need three independently trained copies of a model. We use the same encoder three times, with the same parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*iVtPqoFogVkFkpgegJLZGQ.png" /></figure><p>The anchor is the object we start from. The positive is a different object of the same class. The negative comes from another class. For a tree anchor, another tree is positive and a bridge can be negative.</p><p>Each voxel grid becomes a 256-dimensional vector. The loss encourages the positive to lie closer to the anchor than the negative does. The three forward passes contribute gradients to one shared set of weights.</p><p>The useful shift is from predicting a label directly to learning which examples should be close. That gives us a basis for classification by comparison with labelled references. It does not, of course, create new independent objects out of the thirty we started with.</p><h3>3. A margin is a difference between distances</h3><p>The objective fits on one line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*5rsUJ8bQ7DrwZZxCxh3YUw.png" /></figure><p>Here a, p and n denote the embedding vectors. The loss reaches zero when the negative is at least m farther from the anchor than the positive is. The margin is not a required distance directly between the positive and negative.</p><p>Suppose the two distances are 3 and 8, and the margin is 9. The positive is already closer, but the loss is still 3 − 8 + 9 = 4. If the negative distance becomes 12, the loss reaches zero. Correct ordering and satisfying the margin are different conditions.</p><p>The original settings used nn.TripletMarginLoss(margin=9.0, p=2) with unnormalised embeddings. These are Euclidean distances, not squared Euclidean distances. PyTorch also adds a small numerical-stability term in its distance calculation; the formula above shows the geometric objective. See the <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.TripletMarginLoss.html">PyTorch definition</a>.</p><p>The scale matters. If we normalised every embedding to unit length, Euclidean distances would be at most 2, making a margin of 9 impossible to satisfy. Here the output vectors are not normalised. A margin is a setting for a particular embedding convention, not a number to copy into every metric-learning model.</p><p><a href="https://arxiv.org/abs/1503.03832">FaceNet</a> is a useful reference for the triplet-training idea. Its normalised embeddings and squared-distance formulation are different from the PyTorch configuration used here.</p><h3>4. Small dataset, surprisingly large network</h3><p>The encoder has three blocks of 3D convolution, ReLU and max pooling. The channel counts are 32, 64 and 128. After flattening, two linear layers produce the embedding.</p><pre>class Siamese3DNetwork(nn.Module):<br>    def __init__(self, grid_size=100):<br>        super().__init__()<br>        self.grid_size = grid_size<br>        self.conv_layers = nn.Sequential(<br>            nn.Conv3d(1, 32, 3, padding=1), nn.ReLU(), nn.MaxPool3d(2),<br>            nn.Conv3d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool3d(2),<br>            nn.Conv3d(64, 128, 3, padding=1), nn.ReLU(), nn.MaxPool3d(2),<br>        )<br>        self.fc_layers = nn.Sequential(<br>            nn.Linear(128 * (grid_size // 8) ** 3, 512),<br>            nn.ReLU(), nn.Linear(512, 256),<br>        )<br>    def forward(self, x):<br>        if tuple(x.shape[1:]) != (1, self.grid_size, self.grid_size, self.grid_size):<br>            raise ValueError(&#39;Unexpected voxel tensor shape&#39;)<br>        return self.fc_layers(self.conv_layers(x).flatten(start_dim=1))</pre><p>With a 100 × 100 × 100 input, the spatial sizes after pooling are 50, 25 and 12. Integer rounding matters: the last size is 12, not 12.5. Flattening therefore produces 128 × 12 × 12 × 12 = 221,184 features.</p><p>The first linear layer alone contains 221,184 × 512 = 113,246,208 weights. The whole encoder has 113,655,616 trainable parameters. Simple to describe does not mean small in memory.</p><p>At this resolution, one float32 occupancy grid takes 4 MB. The first convolution produces 32 million float32 values per object, or 128 MB before accounting for the rest of the network. Training on triplets retains several computation graphs, so the batch size has to fit the available memory. The original example used a batch of 8; that is not a hardware-independent recommendation.</p><p>For a new implementation, a smaller grid or pooling before the fully connected layers would be sensible experiments. They would also change the model. The architecture above stays with the one this case study describes.</p><h3>5. Split objects before making triplets</h3><p>With so few examples, data preparation deserves as much attention as the network.</p><p>If we generate many triplets and randomly split them, the same tree can appear in both training and validation. The rows are different, but the object is familiar. Wrapping a triplet-generating dataset in random_split does not, by itself, prevent that dataset from sampling the same underlying object in both partitions.</p><p>The revised example below splits the underlying objects first. Each class folder contains ten LAS files, one independent object per file. Six go to training, two to validation and two to a final test set. This is an illustrative split for the code, not a reconstruction of the historical experiment. Crops or repeated scans of the same physical object must stay together.</p><pre>def split_objects(root, seed=0):<br>    rng = np.random.default_rng(seed)<br>    splits = [[], [], []]<br>    folders = sorted(p for p in Path(root).iterdir() if p.is_dir())<br>    if len(folders) &lt; 2:<br>        raise ValueError(&#39;At least two class folders are required&#39;)<br>    for label, folder in enumerate(folders):<br>        paths = sorted(folder.glob(&#39;*.las&#39;))<br>        if len(paths) != 10:<br>            raise ValueError(&#39;This example expects ten independent objects per class&#39;)<br>        paths = [paths[i] for i in rng.permutation(len(paths))]<br>        for target, chosen in zip(splits, (paths[:6], paths[6:8], paths[8:])):<br>            target.extend((p, label) for p in chosen)<br>    return splits</pre><p>Now form triplets separately within each partition. The positive must differ from the anchor; the negative must have a different class label. For this small example, enumerating the valid combinations is easy:</p><pre>class VoxelTriplets(Dataset):<br>    def __init__(self, records, grid_size=100):<br>        self.voxels = [read_voxel(path, grid_size) for path, _ in records]<br>        labels = np.array([label for _, label in records])<br>        self.triplets = []<br>        for a, label in enumerate(labels):<br>            positives = np.flatnonzero((labels == label) &amp; (np.arange(len(labels)) != a))<br>            negatives = np.flatnonzero(labels != label)<br>            self.triplets.extend((a, int(p), int(n)) for p, n in itertools.product(positives, negatives))<br>        if not self.triplets:<br>            raise ValueError(&#39;Need two objects per class and at least two classes&#39;)<br>    def __len__(self):<br>        return len(self.triplets)<br>    def __getitem__(self, index):<br>        return tuple(self.voxels[i] for i in self.triplets[index])</pre><p>With three classes and six training objects each, there are 18 possible anchors, 5 positives per anchor and 12 negatives: 18 × 5 × 12 = 1,080 ordered triplets. The validation partition produces 6 × 1 × 4 = 24 triplets.</p><p>That is plenty of comparisons, but still only eighteen training objects. Many triplets also become easy once the model separates them. Selecting informative triplets is a possible next step; enumeration here keeps the example explicit and reproducible.</p><h3>6. Train on distance, measure the right thing</h3><p>The training loop runs each member of a triplet through the shared model, calculates the loss and updates the weights. During validation, gradients are disabled.</p><pre>def run_epoch(model, loader, loss_fn, device, optimizer=None):<br>    training = optimizer is not None<br>    model.train(training)<br>    total, loss_sum, ordered = 0, 0.0, 0<br>    with torch.set_grad_enabled(training):<br>        for batch in loader:<br>            a, p, n = [model(x.to(device)) for x in batch]<br>            loss = loss_fn(a, p, n)<br>            if training:<br>                optimizer.zero_grad(set_to_none=True)<br>                loss.backward()<br>                optimizer.step()<br>            count = len(a)<br>            total += count<br>            loss_sum += loss.item() * count<br>            ordered += ((a-p).norm(dim=1) &lt; (a-n).norm(dim=1)).sum().item()<br>    if total == 0:<br>        raise ValueError(&#39;Empty loader&#39;)<br>    return loss_sum / total, ordered / total</pre><p>The loop returns the mean triplet loss and the fraction of triplets in which the positive is closer to the anchor than the negative is. The loss is weighted by the number of triplets in each batch, so a short final batch does not receive the same weight as a full one.</p><p>The second value is a <strong>triplet ordering rate</strong>. It is useful, but it is not object classification accuracy. A model can order a particular positive and negative correctly while another reference from the wrong class is even closer.</p><p>Here is the training setup. The directory objects contains one subdirectory per class. I start the example at batch size 1; it can be increased after checking memory use.</p><pre>torch.manual_seed(0)<br>train_records, val_records, test_records = split_objects(&quot;objects&quot;)<br>grid_size = 100<br>train_loader = DataLoader(VoxelTriplets(train_records, grid_size),<br>                          batch_size=1, shuffle=True)<br>val_loader = DataLoader(VoxelTriplets(val_records, grid_size), batch_size=1)<br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>model = Siamese3DNetwork(grid_size).to(device)<br>loss_fn = nn.TripletMarginLoss(margin=9.0, p=2)<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.001)<br>best_loss = float(&quot;inf&quot;)<br>for epoch in range(30):<br>    train_loss, _ = run_epoch(model, train_loader, loss_fn, device, optimizer)<br>    val_loss, ordering = run_epoch(model, val_loader, loss_fn, device)<br>    print(epoch + 1, train_loss, val_loss, ordering)<br>    if val_loss &lt; best_loss:<br>        best_loss = val_loss<br>        torch.save(model.state_dict(), &quot;best_model.pt&quot;)</pre><p>The best validation-loss checkpoint is selected before looking at the test objects. The test set does not choose the epoch.</p><h3>7. Turn an embedding into a class</h3><p>Triplet loss does not return the words “tree” or “bridge”. We still need a classification rule.</p><p>A straightforward baseline is nearest-reference classification: encode the query, compare it with embeddings of labelled training objects, and return the label of the nearest reference. The same voxelisation and distance convention must be used on both sides.</p><pre>@torch.no_grad()<br>def classify_objects(model, references, queries, device, grid_size=100):<br>    model.eval()<br>    def encode(records):<br>        return torch.cat([<br>            model(read_voxel(path, grid_size).unsqueeze(0).to(device))<br>            for path, _ in records<br>        ])<br>    reference_vectors = encode(references)<br>    query_vectors = encode(queries)<br>    nearest = torch.cdist(query_vectors, reference_vectors).argmin(dim=1).cpu().numpy()<br>    labels = np.array([label for _, label in references])<br>    return labels[nearest]</pre><p>For deployment, reference embeddings can be cached. There is no reason to run the same reference objects through the encoder for every query.</p><pre>model.load_state_dict(torch.load(&quot;best_model.pt&quot;, map_location=device, weights_only=True))<br>predicted = classify_objects(model, train_records, test_records, device, grid_size)<br>expected = np.array([label for _, label in test_records])<br>correct = int((predicted == expected).sum())<br>print(f&quot;{correct}/{len(expected)} objects correct ({correct / len(expected):.1%})&quot;)</pre><p>This final comparison measures object classification accuracy. With the illustrative split, there are only six test objects, so one mistake changes accuracy by about 16.7 percentage points. Reporting the count as well as the percentage makes that scale clear.</p><p>Adding examples of a new class to the reference bank does not require changing an output layer. Whether the existing embedding separates that class well is another question; it still has to be evaluated.</p><h3>What I took away from the project</h3><p>The original prototype came together in a few days and was useful for our narrow set of objects. In the 2024 article, I reported no observed mistakes in the checks we had run. That observation belongs to that project; the published triplet-ordering metric alone cannot establish perfect classification on new objects.</p><p>The part worth carrying forward is the structure of the solution. Voxelisation gave variable-length clouds a consistent input shape. A shared encoder learned a space in which labelled examples could be compared. A reference bank turned those distances into predictions.</p><p>Thirty objects did not suddenly become a large dataset. But changing the question from “learn three output labels” to “learn which objects belong together” gave me a practical route through a problem I had initially decided was too small for a neural network.</p><p>And after the previous project, I was at least no longer spending half the available time figuring out how to open the point cloud. Progress comes in different forms.</p><p><em>Adapted from my </em><a href="https://habr.com/ru/articles/794750/"><em>Russian article published on February 20, 2024</em></a><em>, with revised preprocessing, data splitting and evaluation examples.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b78f612f0ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Labels, No Sleep: Finding Road Defects with LiDAR in 44 Hours]]></title>
            <link>https://medium.com/@HeinrichWirth/no-labels-no-sleep-finding-road-defects-with-lidar-in-44-hours-66187b014f2a?source=rss-5b1baaab6189------2</link>
            <guid isPermaLink="false">https://medium.com/p/66187b014f2a</guid>
            <category><![CDATA[lidar]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Heinrich]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 03:18:10 GMT</pubDate>
            <atom:updated>2026-10-24T05:05:38.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>A hackathon story about RANSAC, point-cloud registration, and finding potholes without a training dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Z30JsBcIBsMGwAQCDWOw_g.png" /></figure><p>How do you detect road defects when nobody has labelled the data? At a hackathon, the obvious answer is: quickly. Preferably before you have spent half the available time figuring out how to open the files.</p><p>We expected video. We got LiDAR.</p><p>Nobody on our team had worked with point clouds before. So our 44-hour task suddenly included learning the data format, getting comfortable with 3D geometry, and building something that could actually find damage in a road surface. Sleep was not doing particularly well in that schedule.</p><p>This is the part I worked on: a geometric pipeline for finding deep depressions in road measurements. No annotated training set, no learned defect classifier. First we had to make the road usable as a reference surface; only then could we ask which points were unusually far below it.</p><p>The route was simple enough on paper: read the recording, level the clouds, align neighbouring frames, select a well-sampled road region, and group low points into pothole candidates. The interesting part was getting those steps to agree with one another.</p><h3>First, open the data. Somehow.</h3><p>The first puzzle was a database file containing binary messages. The organisers’ instruction was to use ROS 2. That sounded like a short preliminary step. Several hours later, it had become a rather substantial part of the hackathon.</p><p>Eventually, we exported the point coordinates to CSV and could start inspecting them with Python. It was not an elegant long-term storage choice, but it let us get to the actual problem.</p><p>Then we plotted the cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*hfw6YyWmIJbfKH86.jpg" /><figcaption>The original point cloud before levelling.</figcaption></figure><p>The road was tilted in the sensor coordinate system. That matters immediately: if I compare heights before accounting for the slope, a perfectly ordinary point farther along the road can look lower than a nearby pothole.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tkT13wuK1E_zZBpr.jpg" /><figcaption>Height colouring makes the tilt of the road surface easier to see.</figcaption></figure><p>We needed a reference plane and a rotation. RANSAC gave us the first; a little linear algebra supplied the second.</p><h3>1. Find the road plane without fitting every stray point</h3><p>A least-squares plane fitted to the whole scene would also try to accommodate objects that are not the road. RANSAC takes a different route: propose a plane from a small random sample, count the points supporting it, and keep the best-supported proposal.</p><p>Three non-collinear points define a plane. Let them be p₁, p₂ and p₃. Their cross product gives a normal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*vPorx52J5MG-J-lrnint8w.png" /></figure><p>The distance from any point p to that plane is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*HUOolYayIfqAQs8KXC4A4w.png" /></figure><p>A point supports the plane when that distance is below a threshold. For example, a threshold of 0.05 means five centimetres if the coordinates are in metres. It is a plane-fitting tolerance, not the minimum pothole depth.</p><p>On each iteration we sample three points, reject a degenerate sample, construct its plane and count the supporting points. The plane with the largest count wins. In our road-dominated scene, that was a useful way to estimate the main road surface.</p><pre>import numpy as np<br>def ransac_plane(points, iterations=1000, threshold=0.05, seed=0):<br>    points = np.asarray(points, dtype=float)<br>    if points.ndim != 2 or points.shape[1] != 3 or len(points) &lt; 3:<br>        raise ValueError(&quot;Expected at least three 3D points&quot;)<br>    if not np.isfinite(points).all() or threshold &lt;= 0:<br>        raise ValueError(&quot;Expected finite coordinates and a positive threshold&quot;)<br>    rng = np.random.default_rng(seed)<br>    best_plane, best_mask = None, np.zeros(len(points), dtype=bool)<br>    for _ in range(iterations):<br>        p, q, r = points[rng.choice(len(points), 3, replace=False)]<br>        normal = np.cross(q - p, r - p)<br>        length = np.linalg.norm(normal)<br>        if length &lt; 1e-12:<br>            continue<br>        normal /= length<br>        offset = -normal @ p<br>        mask = np.abs(points @ normal + offset) &lt; threshold<br>        if mask.sum() &gt; best_mask.sum():<br>            best_plane = np.r_[normal, offset]<br>            best_mask = mask<br>    if best_plane is None:<br>        raise ValueError(&quot;No non-degenerate plane found&quot;)<br>    return best_plane, best_mask</pre><p>The normal is unit-length in this implementation, so the distance calculation in the loop does not need a separate division. Collinear samples are skipped: three points on a line do not define a unique plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*_Si3IXkmC7_m-i3M.png" /><figcaption>Plane fitting on synthetic points: a separate illustration of the RANSAC step.</figcaption></figure><p>For the project implementation, Open3D already provided plane segmentation. Here, point_cloud is the loaded Open3D PointCloud, with coordinates in metres. The settings in the original example were a 0.1 m distance threshold, three sampled points and 4,000 iterations:</p><pre>import open3d as o3d<br>plane_model, inliers = point_cloud.segment_plane(<br>    distance_threshold=0.1,<br>    ransac_n=3,<br>    num_iterations=4000,<br>)</pre><p>Finding the plane does not yet level the cloud. We now know which direction is perpendicular to the road; we still have to rotate that direction onto the vertical axis.</p><h3>2. Make “below the road” mean something</h3><p>Let n̂ be the unit normal and e = (0, 0, 1) the vertical direction. A plane has two equivalent normal directions, so I choose the one with a non-negative vertical component.</p><p>The rotation axis is perpendicular to both n̂ and e. The cross product gives its direction, while the dot product gives the cosine of the angle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*YPFpfTghATuR4CDRsiEmWA.png" /></figure><p>When s is zero, the chosen normal already points up and the identity rotation is enough. Otherwise, build the cross-product matrix from the unit axis u:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*hJM1I9-ysNKB0w8t9BrNCg.png" /></figure><p>This is Rodrigues’ rotation formula. It rotates around the axis we actually computed. A matrix that rotates only around Z would merely turn the road left or right; it would not remove the tilt.</p><pre>def leveling_rotation(normal):<br>    normal = np.asarray(normal, dtype=float)<br>    length = np.linalg.norm(normal)<br>    if not np.isfinite(length) or length &lt; 1e-12:<br>        raise ValueError(&quot;Expected a non-zero finite normal&quot;)<br>    normal = normal / length<br>    if normal[2] &lt; 0:<br>        normal = -normal<br>    vertical = np.array([0., 0., 1.])<br>    cross = np.cross(normal, vertical)<br>    sine = np.linalg.norm(cross)<br>    cosine = np.clip(normal @ vertical, -1., 1.)<br>    if sine &lt; 1e-12:<br>        return np.eye(3)<br>    x, y, z = cross / sine<br>    K = np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]])<br>    return np.eye(3) + sine * K + (1 - cosine) * (K @ K)</pre><p>For an individual column-vector point, the transformation is p′ = Rp. NumPy normally stores a cloud as rows, so the corresponding array operation uses the transpose:</p><pre>points = np.asarray(point_cloud.points)<br>R = leveling_rotation(plane_model[:3])<br>leveled_points = points @ R.T</pre><p>The road plane is now parallel to the XY plane. Its height need not be zero: rotation changes orientation, not the vertical origin. That is fine for the height statistics below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UZDchgLnIeIbYoXc.jpg" /><figcaption>The cloud after rotating the estimated road normal onto the vertical axis.</figcaption></figure><p>Much better. Now we could compare heights without confusing the sensor’s orientation with road damage.</p><h3>3. More frames, more points. Also more opportunities to misalign them.</h3><p>The next problem was density. The individual clouds did not contain enough useful road samples for the defects we wanted to inspect.</p><p>Stacking several frames seemed obvious. But the vehicle moves between frames. Concatenating their coordinates would paint the same road in several different positions, which is an excellent way to manufacture geometry that was never there.</p><p>We used ICP, Iterative Closest Point, to align overlapping clouds before combining them. The idea is to alternate between two questions: which points correspond, and which rigid transformation best aligns those correspondences?</p><p>ICP refines an existing alignment. It needs overlapping views and a reasonable initial pose; it does not magically know where an arbitrary second scan belongs.</p><h3>One ICP iteration, written out</h3><p>For every source point aᵢ, find a nearby target point bᵢ. Here N is the number of accepted pairs, not necessarily the size of either original cloud. With those pairs fixed, solve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*iARvoKihMFCr3l7lzrbkbg.png" /></figure><p>First, compute the centroids and subtract them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*1bx899XDza_jXhOPna2TpA.png" /></figure><p>Now build the cross-covariance matrix and factor it with SVD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*3FTpgeVMVowYXfuEZNn_0g.png" /></figure><p>The rotation and translation follow from that decomposition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VMgsTORTIxCdtOi6ssYkow.png" /></figure><p>The last diagonal entry of D prevents a reflection. We want a rigid rotation, not a mirror-image road. Apply the result to the original, uncentred points in the current iteration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*c_JwFr8Hda7b5y4IQAzQag.png" /></figure><pre>def best_fit_transform(source, target):<br>    source = np.asarray(source, dtype=float)<br>    target = np.asarray(target, dtype=float)<br>    if source.shape != target.shape or source.ndim != 2 or source.shape[1] != 3 or len(source) &lt; 3:<br>        raise ValueError(&quot;Expected equally sized matched 3D arrays&quot;)<br>    a, b = source.mean(axis=0), target.mean(axis=0)<br>    H = (source - a).T @ (target - b)<br>    U, _, Vt = np.linalg.svd(H)<br>    correction = np.eye(3)<br>    correction[2, 2] = np.linalg.det(Vt.T @ U.T)<br>    R = Vt.T @ correction @ U.T<br>    t = b - R @ a<br>    return R, t</pre><p>Then find new nearest neighbours and repeat. A KD-tree makes those queries practical without comparing every source point against every target point.</p><p>There is one easy mistake here: the rotation returned by an iteration only moves the <em>current</em> cloud. To transform the original frame later, we have to accumulate the updates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VWnsvvDv5vW6sF0DcFcn5Q.png" /></figure><pre>from scipy.spatial import cKDTree<br>def icp(source, target, max_distance, iterations=100, tolerance=1e-7):<br>    source = np.asarray(source, dtype=float)<br>    target = np.asarray(target, dtype=float)<br>    aligned = source.copy()<br>    tree = cKDTree(target)<br>    R_total, t_total = np.eye(3), np.zeros(3)<br>    previous_error = np.inf<br>    for _ in range(iterations):<br>        distances, indices = tree.query(aligned)<br>        keep = distances &lt;= max_distance<br>        if keep.sum() &lt; 3:<br>            raise ValueError(&quot;Too few correspondences&quot;)<br>        R, t = best_fit_transform(aligned[keep], target[indices[keep]])<br>        aligned = aligned @ R.T + t<br>        R_total = R @ R_total<br>        t_total = R @ t_total + t<br>        residuals = aligned[keep] - target[indices[keep]]<br>        error = np.sqrt(np.mean(np.sum(residuals ** 2, axis=1)))<br>        if abs(previous_error - error) &lt; tolerance:<br>            break<br>        previous_error = error<br>    return aligned, R_total, t_total</pre><p>This point-to-point example starts from the supplied source coordinates, rejects matches farther than the chosen distance, and returns both the aligned points and the accumulated transformation. Its stopping value is the change in paired RMS error after an update. The distance and tolerance are in the same units as the cloud.</p><p>Once neighbouring frames share a coordinate system, their points can be combined. That increases sampling density; it does not change the accuracy of each individual LiDAR measurement.</p><h3>4. Find the road without throwing away the potholes</h3><p>We now had a levelled, denser cloud. But the scene still contained more than pavement. Under a hackathon deadline, I wanted a cheap way to locate the main road surface.</p><p>The first clue was a histogram of heights. Split the vertical range into 40 bins and count the points in each. In these scenes, the dominant band was a useful indicator of the road level. For a non-zero height range, the bin width is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*_pnlehTFtuar_h07YYneGg.png" /></figure><p>Using NumPy’s histogram directly also handles the upper endpoint consistently. All bins exclude their right edge except the final bin, which includes it.</p><pre>def road_height_band(points, bins=40):<br>    points = np.asarray(points, dtype=float)<br>    heights = points[:, 2]<br>    counts, edges = np.histogram(heights, bins=bins)<br>    index = counts.argmax()<br>    lower, upper = edges[index:index + 2]<br>    mask = (heights &gt;= lower) &amp; (heights &lt; upper)<br>    if index == len(counts) - 1:<br>        mask = (heights &gt;= lower) &amp; (heights &lt;= upper)<br>    return mask, (lower, upper)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*JOf9LD3tPvZA1cbU.jpg" /><figcaption>The dominant height band used to locate the road surface.</figcaption></figure><p><strong>The dense band identifies the surface level; it must not become the final pothole filter.</strong> If we keep only a thin slice around normal pavement height, a deep pothole disappears before the detector ever sees it.</p><p>The original prototype used the height band as a direct filter. In the examples here, I separate surface estimation from defect selection: the band locates the road, while the search region also retains measurements below it. The next step shows how to carry that footprint back to the full cloud using horizontal coordinates.</p><h3>5. Concentrate on the region with enough measurements</h3><p>Even within the road, the sampling was uneven. We concentrated on a well-sampled region around the vehicle instead of treating every sparse patch as equally informative.</p><p>The approach was deliberately economical: sample 10% of the points, run DBSCAN on that subset, then transfer the labels back to the full set using nearest neighbours.</p><p>DBSCAN groups points through local density. A point is a core point when its radius-ε neighbourhood contains at least the required number of samples; connected core neighbourhoods grow into clusters, with nearby border points attached. The remaining points receive the noise label −1.</p><p>The original settings for the sampled road cloud were ε = 0.1 m and 20 points. Those values apply to the sampled density, not automatically to the full cloud.</p><pre>surface_mask, (_, surface_upper) = road_height_band(leveled_points)<br>road_points = leveled_points[surface_mask]<br>if len(road_points) == 0:<br>    raise ValueError(&quot;No points in the road height band&quot;)<br>rng = np.random.default_rng(0)<br>sample_size = max(1, int(0.1 * len(road_points)))<br>indices = rng.choice(len(road_points), sample_size, replace=False)<br>sample = road_points[indices]<br>sample_cloud = o3d.geometry.PointCloud()<br>sample_cloud.points = o3d.utility.Vector3dVector(sample)<br>labels = np.asarray(sample_cloud.cluster_dbscan(<br>    eps=0.1, min_points=20, print_progress=False<br>))</pre><p>Label transfer is an approximation, not DBSCAN run on every point. A distance gate prevents a distant point from inheriting a cluster label. To preserve the road footprint below the surface, the query uses XY coordinates: a pothole point should not be rejected simply because it is lower.</p><pre>from scipy.spatial import cKDTree<br>def transfer_labels(sample, labels, points, max_distance):<br>    distances, indices = cKDTree(sample).query(points)<br>    result = np.full(len(points), -1, dtype=int)<br>    keep = distances &lt;= max_distance<br>    result[keep] = np.asarray(labels)[indices[keep]]<br>    return result</pre><pre>full_labels = transfer_labels(<br>    sample[:, :2], labels, leveled_points[:, :2], max_distance=0.1<br>)<br>full_labels[leveled_points[:, 2] &gt; surface_upper] = -1<br>valid_labels = full_labels[full_labels &gt;= 0]<br>if len(valid_labels) == 0:<br>    raise ValueError(&quot;No supported road cluster&quot;)<br>cluster_ids, counts = np.unique(valid_labels, return_counts=True)<br>largest_id = cluster_ids[counts.argmax()]<br>road_region = leveled_points[full_labels == largest_id]</pre><p>The 0.1 m gate in this example is a horizontal footprint tolerance. Points above the road band are excluded; lower points remain available for the depth test.</p><p>Among the valid clusters, the largest by point count gives a practical working region. Noise is excluded from that choice. “Largest” here means the most assigned points; it does not prove the highest density or make potholes more likely. It simply gives us more measurements to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KP1B8z-OxkqgY4y7.png" /><figcaption>The selected road region for further analysis.</figcaption></figure><h3>6. Look below the surface, then ask whether the points form an object</h3><p>At last, the part that sounds like the original task: finding potholes.</p><p>For the selected road region, calculate the mean height and population standard deviation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*20ttOui6AdwVM2Nf5Ujm2w.png" /></figure><p>The idea is that most measurements describe ordinary pavement, while a deep depression contributes a small group of unusually low points. Four standard deviations is the chosen threshold multiplier, not a measured accuracy or a guarantee about the distribution of road heights.</p><p>For a simple numerical example, if the mean is 0.20 m and the standard deviation is 0.01 m, the cutoff is 0.16 m. A point at 0.14 m is selected; a point at 0.18 m is not. The absolute height origin does not matter, because the threshold moves with the mean.</p><p>One low point still does not make a pothole. We group the selected points using DBSCAN again, this time with ε = 0.06 m and a minimum of three points:</p><pre>heights = road_region[:, 2]<br>cutoff = heights.mean() - 4 * heights.std(ddof=0)<br>low = road_region[heights &lt; cutoff]<br>centres = []<br>if len(low) &gt;= 3:<br>    candidates = o3d.geometry.PointCloud()<br>    candidates.points = o3d.utility.Vector3dVector(low)<br>    labels = np.asarray(candidates.cluster_dbscan(<br>        eps=0.06, min_points=3, print_progress=False<br>    ))<br>    for label in np.unique(labels):<br>        if label == -1:<br>            continue<br>        centres.append(low[labels == label].mean(axis=0))</pre><p>Each centre is the mean of the observed low points in that cluster. It is a location in the cloud’s coordinate system, not latitude and longitude, and not necessarily the physical centre of the entire pothole.</p><p>This approach is aimed at deep depressions on a locally level surface. It does not turn into a detector for every crack just because both are road defects. A broad depression can also shift the mean and increase the standard deviation; the global height test is deliberately a simple baseline.</p><p>Repeated observations need to be merged as well, otherwise driving past one pothole produces several reports. Our post-processing removed repeated detections. For reporting, however, we recorded the vehicle’s position at the time of detection. Converting the actual defect position into map coordinates was still unfinished.</p><h3>What we managed in 44 hours</h3><p>We built a prototype that selected deep pothole candidates from unlabelled LiDAR measurements. Along the way, I had to learn how to work with point clouds, estimate a road plane, align frames and separate geometry worth inspecting from the rest of the scene.</p><p>We did not finish the web interface or the map view. The reported locations were the vehicle’s coordinates rather than properly georeferenced pothole centres. And I could have explained the method much better during the presentation. We finished seventh.</p><p>Not the trophy ending, then. But a useful one.</p><p>The most interesting part was how little of the work was the final threshold. “Find points below the road” fits in a line of code. Making <em>the road</em>, <em>below</em> and <em>the same place in two frames</em> mean something took almost everything before it.</p><p>That was the real lesson of those 44 hours: before asking a detector to find a defect, make sure the geometry gives the question a sensible meaning.</p><p><em>Adapted from my </em><a href="https://habr.com/ru/articles/765230/"><em>Russian article published on October 4, 2023</em></a><em>, with revised Python examples.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66187b014f2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>