メインコンテンツへスキップ
見出し画像

立木の輪切り -点群・太さ計測・相対幹曲線-

    森林調査でLiDARを使っています。使っているのはmapry LA03-1という機種です。最近、メーカーキャンペーンでハードウエアをバージョンアップしました。


    今回のテーマ

    採ったデータはmapry専用の解析アプリで解析し、立木の位置、サイズなどをリストアップする仕掛け。木が立ったままの状態で、手の届かない高さの直径を図ることができたり、木の曲がり具合の判定もしてくれるので、伐採前の売り上げの見込みを立てたり、注文材の選木などに役に立っています。

    画像
    メーカー公式noteより。mapry LA03-1での計測の様子
    画像
    mapryの解析アプリによる立木解析

    メーカー公式noteはこちら。

    ところがちょっと不満な点もあって、mapryの解析では、内部的には地上から10cm間隔で樹頂までの輪切りで幹を測っているってことなんですよ、ところが解析アプリで得られるのは、地際・伐採高さ・胸高直径(1.2m)・そしてユーザが自分で設定する三点、例えば4m・8m・12mといった数点だけなんですね。そして丸太の品質の重要な指標である曲がり、等級判断は、立木全体の曲がりをベースにしています。

    もちろんそれでも通常の業務や調査であれば問題ないんですが、せっかくスキャナで高密度な点群データが得られるわけだから、数百万円クラスのLiDARの解析アプリのように、なんとか任意の間隔で輪切りデータが作れないかな、というのが今回のテーマです。


    mapryでの点群解析の前にやったほうがいいと思うこと

    mapryの点群解析アプリは、専用データだけではなく、LASデータをインポートすることができます。だから一度スキャンデータから生の点群データを作ったら、CloudCompareなどに渡してノイズ除去とサブサンプリングをしたほうがいいと思います。
    地上レーザスキャナで採った点群データは、例えば1cmの格子に多数の点が詰まっているなど、偏りが大きいんですね。それは計測上意味のあるデータにはならないから、一定のボクセル間隔に集約したほうがいいです。うまくするとデータ容量が半分ぐらいになり、計算負荷も下がるしデータのハンドリングも向上します。


    で、いきなりスクリプト

    画像
    tree_slice.py

    まずスクリプト「tree_slice.py」について。あらかじめ、mapryで立木抽出をかけます。胸高直径とか樹高とかいろんなデータが得られるんだけど、ここで作ったshpファイルの属性値から立木の位置情報を拾います。で、この各立木の位置を起点にして、それぞれの立木を地際を0mとして好きな間隔で水平に輪切りにし、断面に円を当てはめて、高さごとに直径と中心の座標を出します。
    実際の木の幹は枝なんかで凸凹してますし、製材して材木になるのは凸凹を取り除いた真ん中です。それで断面の輪郭の内側に収まる最大の円(最大内接円)で太さを決める仕様としました。
    サンプルデータとして、先日採ったデータからスギ137本を、10cm刻み、最大高24mまで輪切りにしてみました。断面の数は33,840面になりました。

    このデータをグラフィカルに表示するために、断面の中心と内接円を点群データに出力するスクリプト「circles_to_csv.py」も作りました。CloudCompareなどで林分の点群データと輪切り位置とサイズが重ねて表示できます。

    画像
    スクリプト:circles_to_csv.py
    向かって右が立木輪切りデータ
    画像
    点群データに輪切り位置と大きさのデータ(csv)を載せる

    何がうれしいか

    何がうれしいのかというと、断面の中心座標を細かく取るところ。
    各段の中心がどれだけブレているかを追えば、幹の曲がり具合を数値で表せるばかりでなく、設定した伐採高からの採材長さの曲がりが抽出できるんです。つまり、立木一本単位の等級ではなく、玉切る丸太の等級が分かる。私らが売ってるのは立木じゃなくて一個づつの玉、丸太ですから。
    例えば、最近の注文材で「7m行って末口65cmで直材」なんてのが実際ありまして、そんなものは普通ない。あっても製材は相当タイトです。
    そんな時、デカい木を探してきて、どこからどこまでを切ったら注文通りになるかを、伐採前に厳密に追い込むツールになるんじゃないかなと思う。

    直径の判定ロジックや実測とのずれは厳密に突き合わせて評価する必要はありますが、まあ今回は試作ということで。


    相対幹曲線を描いてみよう!

    「相対幹曲線」は、サイズの違う木の幹をそれぞれ曲線して重ねてみて、単木や林分ごとの立木の成長の傾向について、例えば細り率など、幹形を評価する手法です。書き方はこうです。

    • 横軸:相対高さ=(樹高−地上高)÷樹高(樹頂が0、地際が1)

    • 縦軸:相対直径=直径÷基準直径(基準直径は「樹高の1割の高さ」の直径)

    • 上の相対高さ・相対直径の組に、原点を通る三次式を当てはめる。

    私は以前、自社山林のスギの細り率の傾向がどうしても知りたくて、大学院で教わったこの図と三次曲線を作ってみたんですよ。その時、実際に十数本、実際に木を切り倒して現物を測りました。

    画像
    現物を計測するのは大変だ。
    長さが30m、重量が3トンぐらいの大根だと思ってください。

    その時思ったんだけど、どの木を伐るのか非常にむつかしいんですね。ランダムサンプリングでいけってことなんだけど、サンプリング数が少なすぎて、結果がどうしても特定の傾向に偏ってしまいます。あまりいいデータが取れなかった。
    それで、伐らないで測る!というLiDARのデータで、サンプル数を全木にまで拡大してみようというのがスクリプト「relative_stem_curve.py」です。

    画像
    relative_stem_curve.py

    面白かったこと①:ノイズは 5–95パーセンタイルの外側に収まる

    全データからそのまま三次曲線を引くと、形が崩れて幹曲線らしくなりません(R²=0.22)。
    どうも測定時のノイズが影響しているようです。LiDARは背負ったり手で持っり、山の傾斜地で滑ったり転んだり、レーザーを一様に照射できてるわけでも反射が拾えているわけでもないからです。

    それで前回の台風進路予測に引き続き、今回もまた糖尿病AGPメソッドの登場です。
    全プロットを5-95パーセンタイルと25-75パーセンタイルに分類し、それぞれのデータだけで三次式を書いてみました。すると、5-95パーセンタイルの曲線も25-75パーセンタイルの曲線もほぼ変化がなかったんですね。結果は以下です。

    • 全データ:係数 1.81, −0.39, −0.43/R² 0.22

    • p5–p95 コア:係数 3.68, −5.57, 3.01/R² 0.73

    • p25–p75 コア:係数 3.67, −5.62, 3.07/R² 0.88

    つまり、p5–p95 の外を外れ値として落とせば、幹曲線は十分きれいに引けるってことかなと。


    面白かったこと②:センサの特性を知れ!

    もう一つ、全立木のプロットで面白いことが見て取れます。

    画像
    データの散らばりがなぜかここだけ収束している

    相対高さ0.4あたりより樹頂側(プロットの左)は、断面に入る点の数が一気に減ってデータがまばらになってます。そこで、相対高さではなく実際の地上高で、断面ごとに2つの値を計算してみました。ひとつは coverage(断面の点が幹の円周をどれだけ取り囲んでいるか、全周に対する割合)、もうひとつは断面に含まれる点の数です。すると、どちらも 1.0〜1.5m で最良になります。そこから樹頂方向へ行くほど coverage も点数も下がり、下側はほとんど変わりません(最下端は地面や下草が混じって少し落ちます)。

    • 1.0–1.5m:coverage 0.667(最良)/点数 237(最多)

    • 4.5–5.0m:coverage 0.583/点数 146

    • 7.0–7.5m:coverage 0.486/点数 98

    たぶん理由は、センサの高さだと思います。mapry LA03-1は背負い式、センサ高はおよそ1.2mになるんですが、この高さに水平な帯で、幹の全周がいちばんよく拾えてるってことなんじゃないか。
    上に行くほどレーザが斜めに当たり、樹冠にも遮られて測定の質が急に落ちる。1.2mが素直なデータをたくさん拾えているのは、「根張りより上・枝より下」という立木の形状的な理由もあるけれど、レーザの走査の幾何的な特性が効いているんじゃないか。このスキャナの特性は案外とピーキーなのかもしれないと思いました。


    明日やります、すぐやります

    使っている人は知っている、地上のLiDARは、樹高を正確に計ることが大変難しい。というのは、一般に市販されているスキャナのレーザ照射範囲は、いいとこ25m程度。また、地上からは葉っぱや枝にさえぎられて、樹頂点は見えないのが普通です。つまり、樹頂点にはレーザが届かないことが多いわけです。
    今回の実験は、地上のLiDARで計測した限りの樹高測定値を使ってますから、そこらいろいろ齟齬があります。精度の高いデータを得ようと思ったら、UAVなどで採った上空からのデータで樹頂点あたりのデータと、航空レーザなどで採った高精度な地表データを持ってきて、こいつを絶対座標ベースで合体させた、全方位的全層的な点群データが必要になります。
    そこらへんは以前この記事に書きました。これで学会論文も書きました。

    これつかってデータ作りなおしてみよう、はい、今すぐやります、すぐやります、はい。


    スクリプト全文

    tree_slice.py

    # -*- coding: utf-8 -*-
    """
    tree_slice.py
    
    Extract trunk cross-section circles (diameter and center) from a forest
    point cloud (LAS), using seed tree positions from a shapefile.
    
    For each seeded tree, the shapefile ground elevation is used as z = 0.
    Horizontal slices are cut at requested heights above ground, a circle is
    fitted to each slice (RANSAC to reject branches / neighbours / understory,
    then Taubin refinement which is low-bias on partial arcs), and the
    diameter and center (x, y) are written per slice.
    
    The REPORTED diameter / center are those of the MAXIMUM INSCRIBED CIRCLE
    of the inlier outline (largest circle fitting inside the cross-section;
    for an elliptical section this approaches the minor axis), not of the
    fitted (approximating) circle. The RANSAC/Taubin fit is still used for
    outlier rejection, slice-to-slice tracking and the quality metrics
    (rmse_m, coverage), which keep describing the fit.
    
    Slice heights are arbitrary:
      --heights "0.5,1.2,4,8,12"          explicit list
      --start 0.5 --stop 12 --step 0.5    regular interval
    
    NOTE on the shapefile: fields are read by COLUMN INDEX (see *_COL below),
    so no Japanese field-name literals appear in this script. The expected
    column order is validated at load time.
    
    Example:
      python tree_slice.py --las cloud.las --shp tree.shp \
          --start 0.5 --stop 24 --step 0.5 --thickness 0.05 --out slices.csv --plot
    """
    import argparse
    import sys
    import numpy as np
    
    try:
        import laspy
    except ImportError:
        sys.exit("laspy is required: pip install laspy lazrs")
    try:
        import shapefile  # pyshp
    except ImportError:
        sys.exit("pyshp is required: pip install pyshp")
    try:
        from scipy.spatial import cKDTree
    except ImportError:
        sys.exit("scipy is required: pip install scipy")
    
    # --- Shapefile column indices (0-based, after the deletion flag) ----------
    # Expected order:
    #   0:ID 1:x 2:y 3:ground_elev 4:dbh(1.2m) 5:d0.5m 6:d4m 7:d8m 8:d12m
    #   9:tree_height 10:crown_base ...
    ID_COL = 0
    GROUND_COL = 3          # ground elevation -> z = 0 reference
    HEIGHT_COL = 9          # tree height
    MIN_FIELDS = 10
    # reference diameters: slice height (m) -> column index
    REF_DIAM_COL = {0.5: 5, 1.2: 4, 4.0: 6, 8.0: 7, 12.0: 8}
    
    
    # ---------------------------------------------------------------------------
    # Circle fitting
    # ---------------------------------------------------------------------------
    def fit_circle_lsq(x, y):
        """Kasa algebraic least-squares circle (used inside RANSAC sampling)."""
        x = np.asarray(x, float)
        y = np.asarray(y, float)
        A = np.column_stack([2 * x, 2 * y, np.ones_like(x)])
        b = x * x + y * y
        sol, *_ = np.linalg.lstsq(A, b, rcond=None)
        cx, cy, c = sol
        r = np.sqrt(max(c + cx * cx + cy * cy, 0.0))
        return cx, cy, r
    
    
    def fit_circle_taubin(x, y):
        """
        Taubin circle fit. Low radius bias on one-sided partial arcs
        (more robust than Kasa). Based on Chernov's implementation.
        """
        x = np.asarray(x, float)
        y = np.asarray(y, float)
        xm, ym = x.mean(), y.mean()
        u, v = x - xm, y - ym
        Zi = u * u + v * v
        Mz = Zi.mean()
        Mxy = (u * v).mean()
        Mxx = (u * u).mean()
        Myy = (v * v).mean()
        Mxz = (u * Zi).mean()
        Myz = (v * Zi).mean()
        Mzz = (Zi * Zi).mean()
        Cov_xy = Mxx * Myy - Mxy * Mxy
        Var_z = Mzz - Mz * Mz
        A3 = 4 * Mz
        A2 = -3 * Mz * Mz - Mzz
        A1 = Var_z * Mz + 4 * Cov_xy * Mz - Mxz * Mxz - Myz * Myz
        A0 = (Mxz * (Mxz * Myy - Myz * Mxy)
              + Myz * (Myz * Mxx - Mxz * Mxy) - Var_z * Cov_xy)
        A22, A33 = A2 + A2, A3 + A3 + A3
        xnew, ynew = 0.0, 1e20
        for _ in range(40):
            yold = ynew
            ynew = A0 + xnew * (A1 + xnew * (A2 + xnew * A3))
            if abs(ynew) > abs(yold):
                break
            Dy = A1 + xnew * (A22 + xnew * A33)
            if Dy == 0:
                break
            xold = xnew
            xnew = xold - ynew / Dy
            if xnew != 0 and abs((xnew - xold) / xnew) < 1e-12:
                break
        DET = xnew * xnew - xnew * Mz + Cov_xy
        if abs(DET) < 1e-12:
            return fit_circle_lsq(x, y)
        xc = (Mxz * (Myy - xnew) - Myz * Mxy) / DET / 2.0
        yc = (Myz * (Mxx - xnew) - Mxz * Mxy) / DET / 2.0
        return xc + xm, yc + ym, np.sqrt(xc * xc + yc * yc + Mz)
    
    
    def fit_circle_ransac(x, y, tol=0.02, iters=300, rng=None,
                          r_min=0.02, r_max=0.6,
                          center_prior=None, center_tol=None):
        """
        RANSAC circle fit.
          tol          inlier band on radial residual (m)
          r_min/max    plausible radius range (m); candidates outside are rejected
          center_prior (x0, y0) expected circle center (seed or previous slice)
          center_tol   reject candidates whose center is farther than this from
                       center_prior (m). Main constraint to drop neighbour stems.
        Returns (cx, cy, r, inlier_mask) or None.
        """
        x = np.asarray(x, float)
        y = np.asarray(y, float)
        n = len(x)
        if n < 3:
            return None
        if rng is None:
            rng = np.random.default_rng(0)
    
        best_mask = None
        best_count = 0
        best_params = None
        for _ in range(iters):
            idx = rng.choice(n, 3, replace=False)
            try:
                cx, cy, r = fit_circle_lsq(x[idx], y[idx])
            except np.linalg.LinAlgError:
                continue
            if not (r_min <= r <= r_max):
                continue
            if center_prior is not None and center_tol is not None:
                if np.hypot(cx - center_prior[0], cy - center_prior[1]) > center_tol:
                    continue
            d = np.abs(np.hypot(x - cx, y - cy) - r)
            mask = d < tol
            cnt = int(mask.sum())
            if cnt > best_count:
                best_count = cnt
                best_mask = mask
                best_params = (cx, cy, r)
    
        if best_params is None or best_count < 3:
            return None
        cx, cy, r = fit_circle_taubin(x[best_mask], y[best_mask])
        d = np.abs(np.hypot(x - cx, y - cy) - r)
        mask = d < tol
        if mask.sum() >= 5:
            cx, cy, r = fit_circle_taubin(x[mask], y[mask])
        else:
            mask = best_mask
        if not (r_min <= r <= r_max):
            return None
        if center_prior is not None and center_tol is not None:
            if np.hypot(cx - center_prior[0], cy - center_prior[1]) > center_tol:
                return None
        return cx, cy, r, mask
    
    
    def _enclosed(x, y, cx, cy):
        """True if the points surround (cx, cy): max angular gap <= 180 deg."""
        ang = np.sort(np.arctan2(y - cy, x - cx))
        if len(ang) < 3:
            return False
        gaps = np.diff(ang)
        wrap = ang[0] + 2 * np.pi - ang[-1]
        return max(gaps.max(), wrap) <= np.pi
    
    
    def max_inscribed_circle(x, y, c0, r_fit, center_prior, center_tol):
        """
        Maximum inscribed circle of the point outline (x, y).
    
        The radius at a candidate center is the distance to the NEAREST point,
        so the circle never crosses the outline; the center is moved to maximise
        that radius (Chebyshev-center style). On an elliptical outline this
        converges to the minor semi-axis. The center is constrained to stay
        within center_tol of center_prior - the same constraint as the RANSAC
        fit. Nelder-Mead handles the non-smooth min-distance objective; the
        search starts from the fitted (Taubin) center c0.
    
        Two guards for partially observed outlines:
          - enclosure: an inscribed circle is undefined for an outline that does
            not surround its center (min-distance grows monotonically away from
            a one-sided arc). If the inliers do not enclose the optimised center
            (max angular gap > 180 deg), the center falls back to the fitted
            center c0 and the radius is the nearest-point distance from there.
          - clamp r <= r_fit: an inscribed radius above the approximating-fit
            radius can only come from extrapolating into the unobserved part of
            the perimeter, so it is capped at r_fit.
    
        Returns (cx, cy, r).
        """
        from scipy.optimize import minimize
        x = np.asarray(x, float)
        y = np.asarray(y, float)
        px, py = float(center_prior[0]), float(center_prior[1])
    
        def neg_min_dist(c):
            d = np.min(np.hypot(x - c[0], y - c[1]))
            over = max(0.0, np.hypot(c[0] - px, c[1] - py) - center_tol)
            return -d + 1e3 * over
    
        res = minimize(neg_min_dist, np.asarray(c0, float),
                       method="Nelder-Mead",
                       options={"xatol": 1e-4, "fatol": 1e-5, "maxiter": 400})
        cx, cy = res.x
        if not _enclosed(x, y, cx, cy):
            cx, cy = float(c0[0]), float(c0[1])
        r = min(float(np.min(np.hypot(x - cx, y - cy))), float(r_fit))
        return float(cx), float(cy), r
    
    
    def circle_quality(x, y, cx, cy, r, mask):
        """Return (rmse, coverage). coverage = fraction of 36 angular bins hit."""
        res = np.hypot(x[mask] - cx, y[mask] - cy) - r
        rmse = float(np.sqrt(np.mean(res ** 2))) if mask.sum() else np.nan
        ang = np.arctan2(y[mask] - cy, x[mask] - cx)
        cover = np.nan
        if mask.sum() >= 2:
            bins = np.zeros(36, bool)
            bins[((ang + np.pi) / (2 * np.pi) * 36).astype(int) % 36] = True
            cover = bins.sum() / 36.0
        return rmse, cover
    
    
    # ---------------------------------------------------------------------------
    # Main
    # ---------------------------------------------------------------------------
    def parse_heights(args):
        if args.heights:
            return [float(h) for h in args.heights.replace(" ", "").split(",") if h]
        n = int(round((args.stop - args.start) / args.step))
        return [round(args.start + i * args.step, 6) for i in range(n + 1)]
    
    
    def main():
        ap = argparse.ArgumentParser(
            description="Trunk slice -> circle fit (diameter and center)")
        ap.add_argument("--las", required=True)
        ap.add_argument("--shp", required=True)
        ap.add_argument("--shp-encoding", default="shift_jis",
                        help="encoding of shapefile dbf (read only)")
        ap.add_argument("--heights", default="", help='e.g. "0.5,1.2,4,8,12"')
        ap.add_argument("--start", type=float, default=0.5)
        ap.add_argument("--stop", type=float, default=12.0)
        ap.add_argument("--step", type=float, default=0.5)
        ap.add_argument("--thickness", type=float, default=0.05,
                        help="half thickness of a slice (m); 0.05 = +/-5cm")
        ap.add_argument("--search-radius", type=float, default=0.5,
                        help="search window radius (m); reach thick trunk surface")
        ap.add_argument("--seed-center-tol", type=float, default=0.12,
                        help="max center offset from seed at the lowest slice (m)")
        ap.add_argument("--lean-tol", type=float, default=0.15,
                        help="max center move between slices (m) = lean allowance")
        ap.add_argument("--taper-grow", type=float, default=0.08,
                        help="allowed radius growth per meter going up (taper)")
        ap.add_argument("--ransac-tol", type=float, default=0.015)
        ap.add_argument("--ransac-iters", type=int, default=400)
        ap.add_argument("--r-max", type=float, default=0.45, help="max radius (m)")
        ap.add_argument("--min-points", type=int, default=12,
                        help="min points to attempt a circle fit")
        ap.add_argument("--out", default="slices.csv")
        ap.add_argument("--plot", action="store_true",
                        help="write per-tree slice panels (English labels)")
        ap.add_argument("--seed", type=int, default=0)
        args = ap.parse_args()
    
        heights = parse_heights(args)
        rng = np.random.default_rng(args.seed)
    
        # --- shapefile seeds (read by column index) ---
        sf = shapefile.Reader(args.shp, encoding=args.shp_encoding)
        fields = sf.fields[1:]
        if len(fields) < MIN_FIELDS:
            sys.exit("Unexpected shapefile: need >= %d fields, got %d"
                     % (MIN_FIELDS, len(fields)))
        trees = []
        for sr in sf.iterShapeRecords():
            px, py = sr.shape.points[0]
            trees.append({
                "id": sr.record[ID_COL],
                "x": px, "y": py,
                "ground": float(sr.record[GROUND_COL]),
                "height": float(sr.record[HEIGHT_COL]),
                "ref": {h: float(sr.record[c]) for h, c in REF_DIAM_COL.items()},
            })
        print("trees=%d  slices=%d  heights=%s"
              % (len(trees), len(heights), heights))
    
        # --- LAS (keep only x,y,z; drop the rest to save memory at stand scale) ---
        las = laspy.read(args.las)
        X = np.asarray(las.x, float)
        Y = np.asarray(las.y, float)
        Z = np.asarray(las.z, float)
        del las
        print("loaded %d points" % len(X))
    
        # Spatial index on XY. Neighbourhood extraction per tree becomes O(log N)
        # instead of scanning all points for every tree, so runtime stays flat as
        # the number of trees grows -> scales to hundreds of stems per hectare.
        kdt = cKDTree(np.column_stack([X, Y]))
        # Per-tree window is the original +/-R0_box square. The KD-tree only
        # accelerates the candidate lookup (query a circle that circumscribes the
        # box, radius R0_box*sqrt(2)); the square filter below then reproduces the
        # exact original candidate set, so results are identical while runtime
        # stays O(log N) per tree -> scales to hundreds of stems per hectare.
        R0_box = args.search_radius + 0.3
        R0_ball = R0_box * 1.5      # > box diagonal (sqrt2); box stays fully inside
    
        rows = []
        per_tree_points = {}
        for t in trees:
            # sort indices ascending so points keep their original LAS array order;
            # RANSAC's random sampling is order-dependent, so this preserves results
            idx = np.sort(np.asarray(kdt.query_ball_point([t["x"], t["y"]], R0_ball),
                                     dtype=np.intp))
            tx, ty, tz = X[idx], Y[idx], Z[idx]
            box = (np.abs(tx - t["x"]) < R0_box) & (np.abs(ty - t["y"]) < R0_box)
            tx, ty, tz = tx[box], ty[box], tz[box]
            h_rel = tz - t["ground"]
    
            cx_prev, cy_prev = t["x"], t["y"]
            r_prev = None
            h_last = 0.0
            tree_plot = []
            for h in sorted(heights):
                zsel = np.abs(h_rel - h) < args.thickness
                sx, sy = tx[zsel], ty[zsel]
                if r_prev is not None:
                    gap = max(args.step, h - h_last)
                    r_cap = min(args.r_max, r_prev * (1 + args.taper_grow * gap))
                    r_floor = max(0.02, r_prev * (1 - 0.12 * gap))
                    cprior = (cx_prev, cy_prev)
                    ctol = min(0.5, args.lean_tol + 0.05 * gap)
                else:
                    r_cap, r_floor = args.r_max, 0.02
                    cprior = (t["x"], t["y"])
                    ctol = args.seed_center_tol
                near = np.hypot(sx - cx_prev, sy - cy_prev) < args.search_radius
                sx, sy = sx[near], sy[near]
    
                row = {"tree_id": t["id"], "height_m": h, "n_points": int(len(sx)),
                       "center_x": np.nan, "center_y": np.nan,
                       "diameter_m": np.nan, "radius_m": np.nan,
                       "rmse_m": np.nan, "coverage": np.nan, "status": "few_pts"}
                if len(sx) >= args.min_points:
                    fit = fit_circle_ransac(
                        sx, sy, tol=args.ransac_tol, iters=args.ransac_iters,
                        rng=rng, r_min=r_floor, r_max=r_cap,
                        center_prior=cprior, center_tol=ctol)
                    if fit is not None:
                        cx, cy, r, mask = fit
                        rmse, cover = circle_quality(sx, sy, cx, cy, r, mask)
                        # reported values = max inscribed circle of the inliers;
                        # the fit (cx, cy, r) keeps driving tracking and QC
                        icx, icy, ir = max_inscribed_circle(
                            sx[mask], sy[mask], (cx, cy), r, cprior, ctol)
                        row.update(center_x=icx, center_y=icy, diameter_m=2 * ir,
                                   radius_m=ir, rmse_m=rmse, coverage=cover,
                                   status="ok")
                        cx_prev, cy_prev, r_prev, h_last = cx, cy, r, h
                        tree_plot.append((h, sx, sy, cx, cy, r, mask,
                                          icx, icy, ir))
                    else:
                        row["status"] = "fit_fail"
                rows.append(row)
            per_tree_points[t["id"]] = tree_plot
    
        # --- CSV (ASCII columns) ---
        cols = ["tree_id", "height_m", "n_points", "center_x", "center_y",
                "diameter_m", "radius_m", "rmse_m", "coverage", "status"]
        import csv
        with open(args.out, "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=cols)
            w.writeheader()
            for r in rows:
                out = {}
                for k in cols:
                    v = r[k]
                    if isinstance(v, float):
                        out[k] = "" if np.isnan(v) else "%.4f" % v
                    else:
                        out[k] = v
                w.writerow(out)
        ok = sum(1 for r in rows if r["status"] == "ok")
        print("wrote %s  (%d/%d slices ok)" % (args.out, ok, len(rows)))
    
        # --- compare with reference diameters when heights coincide ---
        errs = []
        print("\n=== compare with reference diameter "
              "(tree, height, ref, est, diff) [m] ===")
        for t in trees:
            for h, ref_d in t["ref"].items():
                if h not in heights:
                    continue
                m = [r for r in rows if r["tree_id"] == t["id"]
                     and abs(r["height_m"] - h) < 1e-6 and r["status"] == "ok"]
                if m:
                    est = m[0]["diameter_m"]
                    errs.append(est - ref_d)
                    print("  ID%-2s %5.1f  ref=%.3f  est=%.3f  d=%+.3f"
                          % (t["id"], h, ref_d, est, est - ref_d))
        if errs:
            e = np.array(errs)
            print("  --- mean %+.3f / mean|.| %.3f / RMSE %.3f (n=%d)"
                  % (e.mean(), np.abs(e).mean(), np.sqrt((e ** 2).mean()), len(e)))
    
        # --- optional plots (English labels only) ---
        if args.plot:
            try:
                import matplotlib
                matplotlib.use("Agg")
                import matplotlib.pyplot as plt
            except ImportError:
                print("matplotlib not available; skipping plots")
                return
            for tid, tp in per_tree_points.items():
                if not tp:
                    continue
                ncol = min(5, len(tp))
                nrow = int(np.ceil(len(tp) / ncol))
                fig, axes = plt.subplots(nrow, ncol, figsize=(3 * ncol, 3 * nrow))
                axes = np.atleast_1d(axes).ravel()
                for ax, (h, sx, sy, cx, cy, r, mask,
                         icx, icy, ir) in zip(axes, tp):
                    ax.scatter(sx[~mask], sy[~mask], s=3, c="0.7")
                    ax.scatter(sx[mask], sy[mask], s=3, c="tab:blue")
                    th = np.linspace(0, 2 * np.pi, 100)
                    ax.plot(cx + r * np.cos(th), cy + r * np.sin(th),
                            "--", color="0.5", lw=0.8)          # fitted circle
                    ax.plot(icx + ir * np.cos(th), icy + ir * np.sin(th),
                            "r-", lw=1)                          # inscribed
                    ax.plot(icx, icy, "r+")
                    ax.set_title("h=%gm D=%.3fm (fit %.3f)"
                                 % (h, 2 * ir, 2 * r), fontsize=8)
                    ax.set_aspect("equal")
                    ax.tick_params(labelsize=6)
                for ax in axes[len(tp):]:
                    ax.axis("off")
                fig.suptitle("Tree ID %s" % tid)
                fig.tight_layout()
                out = "tree_%s_slices.png" % tid
                fig.savefig(out, dpi=120)
                plt.close(fig)
                print("  plot: %s" % out)
    
    
    if __name__ == "__main__":
        main()
    

    circles_to_csv.py

    # -*- coding: utf-8 -*-
    """
    circles_to_csv.py
    
    Export fitted trunk circles (tree_slice.py output) as a simple point CSV for
    overlay on the original point cloud in CloudCompare.
    
    Output: circles_points.csv with columns  x, y, z, diameter_m
      - points = each circle's center plus sampled perimeter points
      - x, y, z are ABSOLUTE coordinates (same system as the original LAS)
        z = (shapefile ground elevation of the tree) + (slice height above ground)
      - diameter_m is carried as a scalar so CloudCompare can colour by it
    
    ASCII / English only. Seed shapefile fields read by COLUMN INDEX.
    
    Example:
      python circles_to_csv.py --csv slices_full.csv \
          --shp mapry/clip/clip_table/tree.shp --n 72 --out circles_points.csv
    """
    import argparse, csv, sys
    import numpy as np
    import shapefile
    
    ID_COL = 0
    GROUND_COL = 3   # ground elevation -> z = 0 reference per tree
    
    
    def main():
        ap = argparse.ArgumentParser()
        ap.add_argument("--csv", default="slices_full.csv")
        ap.add_argument("--shp", default="mapry/clip/clip_table/tree.shp")
        ap.add_argument("--shp-encoding", default="shift_jis")
        ap.add_argument("--n", type=int, default=72,
                        help="perimeter sample points per circle")
        ap.add_argument("--out", default="circles_points.csv")
        args = ap.parse_args()
    
        sf = shapefile.Reader(args.shp, encoding=args.shp_encoding)
        ground = {sr.record[ID_COL]: float(sr.record[GROUND_COL])
                  for sr in sf.iterShapeRecords()}
    
        ang = -2.0 * np.pi * np.arange(args.n) / args.n
        rows = []  # (x, y, z, diameter)
        with open(args.csv, encoding="utf-8") as f:
            for row in csv.DictReader(f):
                if row.get("status") != "ok" or not row["radius_m"]:
                    continue
                tid = int(row["tree_id"])
                if tid not in ground:
                    continue
                cx = float(row["center_x"]); cy = float(row["center_y"])
                r = float(row["radius_m"]); d = float(row["diameter_m"])
                z = ground[tid] + float(row["height_m"])
                rows.append((cx, cy, z, d))                       # center
                for a in ang:                                      # perimeter
                    rows.append((cx + r * np.cos(a), cy + r * np.sin(a), z, d))
        if not rows:
            sys.exit("no valid circles in CSV")
    
        with open(args.out, "w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(["x", "y", "z", "diameter_m"])
            for x, y, z, d in rows:
                w.writerow(["%.4f" % x, "%.4f" % y, "%.4f" % z, "%.4f" % d])
        print("wrote %s  (%d points)" % (args.out, len(rows)))
    
    
    if __name__ == "__main__":
        main()
    

    relative_stem_curve.py

    # -*- coding: utf-8 -*-
    """
    relative_stem_curve.py  --  relative stem curve by the standard (Behre-type)
    method, after Mitsukado et al. (Shinshu Univ. / Chubu Forest Mgmt Office):
    "Stem taper equation from mobile laser scanning".
    
    Method (per that paper):
      relative height    Hx = (tree_height - h) / tree_height     (tip 0, base 1)
      reference diameter ds = stem diameter at 0.1 * tree_height
                              -- obtained NOT from the raw slice at 0.1H but by
                              fitting a per-tree 3rd-order polynomial d(h) and
                              evaluating it at 0.1H, to avoid knots / local
                              deformation at that single height.
      relative diameter  Dx = d / ds
      stem curve         3rd-order polynomial through the origin
                              Dx = a1*Hx + a2*Hx^2 + a3*Hx^3   (tip: Hx=0, Dx=0)
    
    Tree height is the value the sensor (mapry analysis) reports, read straight
    from the seed shapefile (HEIGHT_COL) and used as measured. Its accuracy is a
    matter for how the source data is produced, not for this script.
    
    The stem curve is fit THREE times, on progressively trimmed inlier sets, so
    the effect of slice-noise tails on the fitted shape is visible:
      - all data
      - 5-95 percentile core   (per relative-height bin)
      - 25-75 percentile core  (per relative-height bin)
    
    Shapefile fields are read by COLUMN INDEX, so no Japanese literals appear.
    
    Examples:
      python relative_stem_curve.py --csv slices_full.csv --shp all_table/tree.shp
    """
    import argparse, csv, sys
    import numpy as np
    import shapefile
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    
    ID_COL = 0
    HEIGHT_COL = 9          # tree height (sensor value), used as measured
    
    # fitted stem curves: (label, percentile core or None for all, colour, style)
    FITS = [
        ("all data", None, "0.4", "--"),
        ("p5-p95 core", (5, 95), "tab:green", "-"),
        ("p25-p75 core", (25, 75), "navy", "-"),
    ]
    
    
    def per_tree_curve(h, d, H, ref_frac, deg, min_points):
        """
        One tree -> (ds, relative_height[], relative_diameter[]) or None.
    
        H  = tree height (sensor value, passed in -- not derived here)
        ds = d(ref_frac*H) from a per-tree degree-`deg` polynomial fit of d(h)
        Skips the tree if too few points, if ref_frac*H would be an extrapolation
        (outside the measured height span), or if ds is non-positive.
        """
        h = np.asarray(h, float)
        d = np.asarray(d, float)
        if len(h) < min_points or H <= 0:
            return None
        h_ref = ref_frac * H
        if h_ref < h.min() or h_ref > h.max():
            return None
        coeffs = np.polyfit(h, d, min(deg, len(h) - 1))
        ds = float(np.polyval(coeffs, h_ref))
        if ds <= 0:
            return None
        return ds, (H - h) / H, d / ds
    
    
    def fit_origin_poly(x, y, deg):
        """Least-squares y = a1*x + a2*x^2 + ... + adeg*x^deg (through origin)."""
        A = np.column_stack([x ** k for k in range(1, deg + 1)])
        coef, *_ = np.linalg.lstsq(A, y, rcond=None)
        yhat = A @ coef
        ss_res = float(np.sum((y - yhat) ** 2))
        ss_tot = float(np.sum((y - y.mean()) ** 2))
        r2 = 1.0 - ss_res / ss_tot if ss_tot > 0 else np.nan
        return coef, r2
    
    
    def eval_origin_poly(coef, x):
        return sum(c * x ** (k + 1) for k, c in enumerate(coef))
    
    
    def pct_mask(x, y, lo, hi, binw=0.05):
        """Keep points whose Dx is within the per-Hx-bin [lo, hi] percentile."""
        x = np.asarray(x, float)
        y = np.asarray(y, float)
        mask = np.zeros(len(x), bool)
        edges = np.arange(0.0, 1.0 + binw, binw)
        idx = np.digitize(x, edges)
        for b in np.unique(idx):
            sel = idx == b
            if sel.sum() < 4:
                continue
            plo, phi = np.percentile(y[sel], [lo, hi])
            mask[sel] = (y[sel] >= plo) & (y[sel] <= phi)
        return mask
    
    
    def band(curves, grid):
        """Per-grid median and percentile bands across trees (no extrapolation)."""
        M = np.full((len(curves), len(grid)), np.nan)
        for i, (x, y) in enumerate(curves):
            o = np.argsort(x)
            xs, ys = x[o], y[o]
            inside = (grid >= xs.min()) & (grid <= xs.max())
            M[i, inside] = np.interp(grid[inside], xs, ys)
        ok = np.sum(~np.isnan(M), axis=0) >= 3
        with np.errstate(all="ignore"):
            med = np.nanmedian(M, axis=0)
            p5, p95 = np.nanpercentile(M, 5, axis=0), np.nanpercentile(M, 95, axis=0)
            p25, p75 = np.nanpercentile(M, 25, axis=0), np.nanpercentile(M, 75, axis=0)
        return ok, med, p5, p95, p25, p75
    
    
    def draw_panel(ax, title, curves, grid, deg):
        """Scatter + percentile bands + three origin-through cubic fits.
    
        Returns [(label, coef, r2, n_points), ...] for the three fits.
        """
        for x, y in curves:
            o = np.argsort(x)
            ax.plot(x[o], y[o], "-", color="0.78", lw=0.6, zorder=1)
            ax.plot(x, y, "o", color="0.6", ms=2.2, mfc="none", zorder=1)
        okm, med, p5, p95, p25, p75 = band(curves, grid)
        g = grid[okm]
        ax.fill_between(g, p5[okm], p95[okm], color="tab:red", alpha=0.12,
                        label="data p5-p95", zorder=2)
        ax.fill_between(g, p25[okm], p75[okm], color="tab:red", alpha=0.25,
                        label="data p25-p75", zorder=3)
    
        allx = np.concatenate([x for x, _ in curves])
        ally = np.concatenate([y for _, y in curves])
        xs = np.linspace(0, 1.0, 200)
        out = []
        for label, pct, color, ls in FITS:
            if pct is None:
                xf, yf = allx, ally
            else:
                m = pct_mask(allx, ally, pct[0], pct[1])
                xf, yf = allx[m], ally[m]
            coef, r2 = fit_origin_poly(xf, yf, deg)
            ax.plot(xs, eval_origin_poly(coef, xs), ls, color=color, lw=2.0,
                    label="fit %s  n=%d R2=%.3f" % (label, len(xf), r2), zorder=5)
            out.append((label, coef, r2, len(xf)))
    
        ax.set_xlim(0.0, 1.0)
        ax.set_ylim(0, 1.6)
        ax.set_xlabel("Relative height  Hx = (H - h) / H   [tip 0 .. base 1]")
        ax.set_ylabel("Relative diameter  Dx = d / d(0.1H)")
        ax.set_title(title)
        ax.grid(alpha=0.3)
        ax.legend(loc="upper left", fontsize=8)
        return out
    
    
    def main():
        ap = argparse.ArgumentParser()
        ap.add_argument("--csv", default="slices_full.csv")
        ap.add_argument("--shp", default="all_table/tree.shp",
                        help="seed shp; supplies tree height (read as measured)")
        ap.add_argument("--shp-encoding", default="shift_jis")
        ap.add_argument("--out", default="relative_stem_curve.png")
        ap.add_argument("--ref-frac", type=float, default=0.1,
                        help="reference diameter height as a fraction of H (0.1H)")
        ap.add_argument("--poly-deg", type=int, default=3)
        ap.add_argument("--grid-step", type=float, default=0.02)
        ap.add_argument("--min-points", type=int, default=6,
                        help="min ok slices per tree to build its curve")
        args = ap.parse_args()
        sys.stdout.reconfigure(encoding="utf-8")
    
        # --- measured slices per tree ---
        meas = {}
        with open(args.csv, encoding="utf-8") as f:
            for row in csv.DictReader(f):
                if row.get("status") != "ok":
                    continue
                tid = int(row["tree_id"])
                meas.setdefault(tid, []).append(
                    (float(row["height_m"]), float(row["diameter_m"])))
        if not meas:
            sys.exit("no rows with status=ok in CSV")
    
        # --- tree height (sensor value), by column index ---
        sf = shapefile.Reader(args.shp, encoding=args.shp_encoding)
        H_shp = {sr.record[ID_COL]: float(sr.record[HEIGHT_COL])
                 for sr in sf.iterShapeRecords()}
    
        grid = np.arange(0.0, 1.0 + args.grid_step, args.grid_step)
    
        curves, used, skipped = [], [], []
        for tid in sorted(meas):
            if tid not in H_shp:
                skipped.append(tid)
                continue
            h = [p[0] for p in meas[tid]]
            d = [p[1] for p in meas[tid]]
            r = per_tree_curve(h, d, H_shp[tid], args.ref_frac,
                               args.poly_deg, args.min_points)
            if r is None:
                skipped.append(tid)
                continue
            _, relh, reld = r
            curves.append((relh, reld))
            used.append(tid)
        if not curves:
            sys.exit("no tree had enough slices to build a curve")
        print("%d trees used, %d skipped (too few/range): %s"
              % (len(used), len(skipped), skipped))
    
        fig, ax = plt.subplots(figsize=(8, 6))
        fits = draw_panel(ax, "Measured relative stem curve (%d trees)" % len(used),
                          curves, grid, args.poly_deg)
        for label, coef, r2, n in fits:
            print("fit %-12s Dx = %.4f*Hx + %.4f*Hx^2 + %.4f*Hx^3  (R2=%.3f, n=%d)"
                  % (label, coef[0], coef[1], coef[2], r2, n))
        fig.tight_layout()
        fig.savefig(args.out, dpi=130)
        print("saved", args.out)
    
    
    if __name__ == "__main__":
        main()
    

    参考文献

    光門舞花・加藤正人ほか:モバイル型レーザを用いた幹曲線式の作成.信州大学/林野庁. 中部森林管理局 技術研究発表会(中部01-125)


    今回も勉強になりました。ということで次回に続く。


     
     
    #うすき林業 #杣人工房うすき #林業 #山林伐採 #丸太販売 #木工 #林学 #社会人大学院

    あなたへのおすすめ