|
|
@@ -0,0 +1,304 @@
|
|
|
+"""单图逐步可视化 evidence_v2 判定链(12 宫格)。
|
|
|
+
|
|
|
+用法:
|
|
|
+ python scripts/vis_evidence_v2_steps.py <image> [<output_dir>]
|
|
|
+"""
|
|
|
+import math
|
|
|
+import os
|
|
|
+import sys
|
|
|
+
|
|
|
+import cv2
|
|
|
+import numpy as np
|
|
|
+import matplotlib
|
|
|
+matplotlib.use("Agg")
|
|
|
+import matplotlib.pyplot as plt
|
|
|
+from matplotlib.patches import Rectangle
|
|
|
+
|
|
|
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
+sys.path.insert(0, ROOT)
|
|
|
+
|
|
|
+from portcv.config import load_config
|
|
|
+from portcv.logic.evidence_v2 import (
|
|
|
+ EvidenceV2, horizontal_bands, pick_box_and_bed, ground_like_ratio,
|
|
|
+ detect_structure_v2, detect_hoist_high, _to_gray, _cluster_positions,
|
|
|
+ content_band,
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+def main() -> int:
|
|
|
+ if len(sys.argv) < 2:
|
|
|
+ print(__doc__)
|
|
|
+ return 2
|
|
|
+ img_file = sys.argv[1]
|
|
|
+ out_dir = sys.argv[2] if len(sys.argv) > 2 else os.path.join(ROOT, "runs", "yolo_vis_steps")
|
|
|
+ os.makedirs(out_dir, exist_ok=True)
|
|
|
+
|
|
|
+ cfg = load_config(os.path.join(ROOT, "configs", "edge-v2-front.json"))
|
|
|
+ ev = EvidenceV2.from_config(cfg)
|
|
|
+ p = ev.p
|
|
|
+ fn = os.path.basename(img_file)
|
|
|
+ image = cv2.imread(img_file)
|
|
|
+ if image is None:
|
|
|
+ print("cannot read", img_file)
|
|
|
+ return 1
|
|
|
+ gray0 = _to_gray(image)
|
|
|
+ h, w = gray0.shape[:2]
|
|
|
+ scale = min(1.0, float(p.work_width) / float(w))
|
|
|
+ gray = cv2.resize(gray0, (int(round(w*scale)), int(round(h*scale))), interpolation=cv2.INTER_AREA) if scale < 1 else gray0.copy()
|
|
|
+ wh, ww = gray.shape[:2]
|
|
|
+
|
|
|
+ window = (int(p.window[0]*ww), int(p.window[1]*wh), int(p.window[2]*ww), int(p.window[3]*wh))
|
|
|
+ max_h = max(6, int(p.band_max_h_ratio*wh))
|
|
|
+ min_h_used = max(1, int(p.band_min_h*scale))
|
|
|
+ bright, dark = horizontal_bands(gray, window, min_h=min_h_used, max_h=max_h)
|
|
|
+ band_top, band_bottom = content_band(
|
|
|
+ gray, window, sky_delta=p.content_sky_delta,
|
|
|
+ hold_rows=p.content_hold_rows, margin_ratio=p.content_margin_ratio,
|
|
|
+ enabled=p.content_filter_enabled)
|
|
|
+ dark_in_content = [b for b in dark if b.y0 >= band_top and b.y0 <= band_bottom]
|
|
|
+ box_hint = max(80.0, 0.40*wh)
|
|
|
+ box, bed = pick_box_and_bed(bright, dark_in_content, wh,
|
|
|
+ box_bottom_max_ratio=p.box_bottom_max_ratio,
|
|
|
+ bed_search_px=max(24.0, p.bed_search_ratio*box_hint))
|
|
|
+ if box is None:
|
|
|
+ print("NO_BOX")
|
|
|
+ return 0
|
|
|
+
|
|
|
+ by0 = window[1]
|
|
|
+ crop = cv2.GaussianBlur(gray[window[1]:window[3], window[0]:window[2]].astype(np.float32), (3,3), 0)
|
|
|
+ gy_prof = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
|
|
|
+ mag = np.abs(gy_prof)
|
|
|
+ limit = float(mag.mean()+0.9*mag.std())
|
|
|
+ min_sep = max(2, int(round(min_h_used)))
|
|
|
+ cand = [i for i in range(1, len(mag)-1) if mag[i]>=limit and mag[i]>=mag[i-1] and mag[i]>=mag[i+1]]
|
|
|
+ picked = []
|
|
|
+ for i in sorted(cand, key=lambda j: mag[j], reverse=True):
|
|
|
+ if all(abs(i-j)>=min_sep for j in picked):
|
|
|
+ picked.append(i)
|
|
|
+ picked.sort()
|
|
|
+
|
|
|
+ px_per_m, vertical_run = ev._scale_from_vertical(gray, box, window, scale)
|
|
|
+ sx0, sy0, sx1, _ = window
|
|
|
+ scrop = gray[max(0,sy0):max(1,int(box.y0)), max(0,sx0):min(gray.shape[1],sx1)]
|
|
|
+ scale_lines, scale_best, best_dy = [], None, 0.0
|
|
|
+ if scrop.size:
|
|
|
+ se = cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(scrop), 50, 150)
|
|
|
+ sl = cv2.HoughLinesP(se, 1, math.pi/180.0, threshold=24,
|
|
|
+ minLineLength=max(12, int(round(getattr(p, 'min_scale_px', 60)*scale))),
|
|
|
+ maxLineGap=max(4, int(round(10*scale))))
|
|
|
+ if sl is not None:
|
|
|
+ for raw in np.asarray(sl).reshape(-1,4):
|
|
|
+ xa, ya, xb, yb = (float(v) for v in raw)
|
|
|
+ dx, dy = abs(xb-xa), abs(yb-ya)
|
|
|
+ if dy >= 2.0*dx:
|
|
|
+ scale_lines.append((xa+sx0, ya+sy0, xb+sx0, yb+sy0))
|
|
|
+ if dy > best_dy:
|
|
|
+ best_dy, scale_best = dy, (xa+sx0, ya+sy0, xb+sx0, yb+sy0)
|
|
|
+ box_h_px = px_per_m*p.box_height_m if px_per_m is not None else None
|
|
|
+ box_top = max(0.0, box.y1/max(scale,1e-6)-box_h_px) if box_h_px else None
|
|
|
+ probe_top = float(box_top) if box_top is not None else max(0.0, box.y0/max(scale,1e-6)-0.35*h)
|
|
|
+ hoist_flag, hoist_cues = detect_hoist_high(
|
|
|
+ gray0, probe_top, dark_max=p.hoist_dark_max, band_frac=p.hoist_band_frac,
|
|
|
+ line_ratio=p.hoist_line_ratio, dark_ratio=p.hoist_dark_ratio,
|
|
|
+ bright_delta=p.hoist_bright_delta)
|
|
|
+
|
|
|
+ est_h = max(60.0, box.y0-0.05*wh)
|
|
|
+ start = max(2.0, p.below_start_ratio*est_h)
|
|
|
+ min_below_h = p.below_min_height_px*max(scale,1e-6)
|
|
|
+ if (wh-1)-box.y1 <= start+min_below_h:
|
|
|
+ start = 2.0
|
|
|
+ y0w = min(wh-2, int(math.ceil(box.y1+start)))
|
|
|
+ below_h = max(min_below_h, min(p.below_height_ratio*est_h, 0.30*wh))
|
|
|
+ y1w = min(wh-1, max(y0w+below_h, box.y1+0.10*est_h))
|
|
|
+ x0w = max(0, int(0.05*ww))
|
|
|
+ x1w = min(ww-1, int(0.95*ww))
|
|
|
+ below_work = (x0w, y0w, x1w, max(y0w+8, int(y1w)))
|
|
|
+
|
|
|
+ structure = detect_structure_v2(gray, below_work, min_post_len_ratio=p.min_post_len_ratio,
|
|
|
+ cluster_gap_px=9.0, scale=scale)
|
|
|
+ posts_n = int(structure["post_count"])
|
|
|
+ ground, gblocks = ground_like_ratio(gray, below_work, structure["lines"],
|
|
|
+ block_px=p.ground_block_px,
|
|
|
+ density_lo=p.ground_density_lo,
|
|
|
+ density_hi=p.ground_density_hi)
|
|
|
+ opacity = max(0.0, min(1.0, 1.0-ground)) if gblocks > 0 else 0.0
|
|
|
+ below_h_work = max(1.0, below_work[3]-below_work[1])
|
|
|
+ deck_min_len = max(20.0, p.deck_min_len_ratio*0.55*ww)
|
|
|
+ deck_segs = [s for s in structure["horizontal"]
|
|
|
+ if box.y1-2.0 <= s["y"] <= box.y1+0.35*below_h_work
|
|
|
+ and s["length"] >= deck_min_len]
|
|
|
+ deck_edge = len(deck_segs) > 0
|
|
|
+ gap_px = max(0.0, (bed.y0-box.y1)/max(scale,1e-6)) if bed is not None else None
|
|
|
+
|
|
|
+ state, conf, hits, reason = ev._classify(
|
|
|
+ posts=posts_n, spacing_cv=structure["post_spacing_cv"], opacity=opacity,
|
|
|
+ ground=ground, deck=deck_edge, wheels=0, gap_px=gap_px,
|
|
|
+ motion_ok=True, view=p.view)
|
|
|
+
|
|
|
+ rx0, ry0, rx1, ry1 = below_work
|
|
|
+ gcrop = gray[ry0:ry1, rx0:rx1]
|
|
|
+ gx = cv2.Sobel(gcrop, cv2.CV_32F, 1, 0, ksize=3)
|
|
|
+ gyy = cv2.Sobel(gcrop, cv2.CV_32F, 0, 1, ksize=3)
|
|
|
+ gmag = np.sqrt(gx*gx + gyy*gyy)
|
|
|
+ hot = gmag > float(np.percentile(gmag, 60.0))
|
|
|
+ bpx = max(6, int(p.ground_block_px))
|
|
|
+ block_info = []
|
|
|
+ for by in range(0, gcrop.shape[0], bpx):
|
|
|
+ for bxx in range(0, gcrop.shape[1], bpx):
|
|
|
+ ex_, ey_ = min(gcrop.shape[1], bxx+bpx), min(gcrop.shape[0], by+bpx)
|
|
|
+ blk = hot[by:ey_, bxx:ex_]
|
|
|
+ if blk.size == 0:
|
|
|
+ continue
|
|
|
+ dens = float(blk.mean())
|
|
|
+ long_line = any(
|
|
|
+ float(s["length"]) >= 0.6*bpx
|
|
|
+ and rx0+bxx <= (s["x0"]+s["x1"])*0.5 <= rx0+ex_
|
|
|
+ and ry0+by <= (s["y0"]+s["y1"])*0.5 <= ry0+ey_
|
|
|
+ for s in structure["lines"])
|
|
|
+ is_g = (not long_line) and p.ground_density_lo <= dens <= p.ground_density_hi
|
|
|
+ block_info.append((bxx, by, ex_, ey_, dens, is_g))
|
|
|
+
|
|
|
+ STATE_NAME = {0: "0 NOT_ON_TRAIN", 1: "1 BED(gondola)", 2: "2 FLATBED", 255: "255 UNKNOWN"}
|
|
|
+ bed_ok = (p.min_door_posts <= posts_n <= p.max_door_posts
|
|
|
+ and opacity >= p.min_wall_opacity
|
|
|
+ and (gap_px is None or gap_px <= p.max_bed_gap_px)
|
|
|
+ and (structure["post_spacing_cv"] is None
|
|
|
+ or structure["post_spacing_cv"] <= p.max_post_spacing_cv))
|
|
|
+ flat_ok = (posts_n <= p.flat_max_door_posts and deck_edge
|
|
|
+ and (gap_px is None or gap_px <= p.max_flat_gap_px))
|
|
|
+ zero_ok = (posts_n <= 1 and ground >= p.min_zero_ground_ratio and not deck_edge)
|
|
|
+ card = [
|
|
|
+ "DECISION CARD (work %dx%d scale=%.3f)" % (ww, wh, scale),
|
|
|
+ "[bands] bright=%d dark=%d box_hint=%.0f" % (len(bright), len(dark), box_hint),
|
|
|
+ "[box] y=%.1f..%.1f bed=%s" % (box.y0, box.y1,
|
|
|
+ "None" if bed is None else "%.1f..%.1f" % (bed.y0, bed.y1)),
|
|
|
+ "[gap_px] %s (<=40)" % ("None" if gap_px is None else "%.1f" % gap_px),
|
|
|
+ "[scale] px/m=%s box_top=%s bestline=%s" % (
|
|
|
+ "None" if px_per_m is None else "%.1f" % px_per_m,
|
|
|
+ "None" if box_top is None else "%.0f" % box_top,
|
|
|
+ "None" if scale_best is None else "%.0fpx" % best_dy),
|
|
|
+ "[hoist] flag=%s lines=%s cables=%s" % (
|
|
|
+ hoist_flag, hoist_cues.get("horizontal_lines"), hoist_cues.get("cables")),
|
|
|
+ "[ROI] below=%s h=%.0f" % (str(below_work), below_h_work),
|
|
|
+ "[struct] posts=%d vlines=%d hlines=%d rect=%d diag=%d" % (
|
|
|
+ posts_n, structure["vertical_lines"], structure["horizontal_lines"],
|
|
|
+ structure["rect_doors"], structure["diagonal_lines"]),
|
|
|
+ "[spacing] median=%s cv=%s (<=6.0)" % (
|
|
|
+ "None" if structure["post_spacing_median"] is None else "%.1f" % structure["post_spacing_median"],
|
|
|
+ "None" if structure["post_spacing_cv"] is None else "%.2f" % structure["post_spacing_cv"]),
|
|
|
+ "[texture] ground=%.2f opacity=%.2f" % (ground, opacity),
|
|
|
+ "[deck] %s minlen=%.0fpx found=%d" % (deck_edge, deck_min_len, len(deck_segs)),
|
|
|
+ "", "bed_strong = %s" % ("YES" if bed_ok else "no"),
|
|
|
+ "flat_strong= %s" % ("YES" if flat_ok else "no"),
|
|
|
+ "zero = %s" % ("YES" if zero_ok else "no"), "",
|
|
|
+ "=> cand=%d (%s) conf=%.2f hits=%.2f reason=%s" % (
|
|
|
+ state, STATE_NAME.get(state, "?"), conf, hits, reason),
|
|
|
+ ]
|
|
|
+
|
|
|
+ fig, axes = plt.subplots(3, 4, figsize=(24, 15))
|
|
|
+ fig.suptitle("Pipeline step visualization: %s" % fn[:70], fontsize=13)
|
|
|
+
|
|
|
+ def panel(ax, img, title, cmap="gray"):
|
|
|
+ ax.imshow(img, cmap=cmap)
|
|
|
+ ax.set_title(title, fontsize=10)
|
|
|
+ ax.axis("off")
|
|
|
+
|
|
|
+ ax = axes[0, 0]
|
|
|
+ panel(ax, gray, "1. Input + window(green) + below-ROI(yellow)")
|
|
|
+ ax.add_patch(Rectangle((window[0], window[1]), window[2]-window[0], window[3]-window[1],
|
|
|
+ fill=False, edgecolor="lime", lw=1.5))
|
|
|
+ ax.add_patch(Rectangle((x0w, y0w), x1w-x0w, below_work[3]-y0w,
|
|
|
+ fill=False, edgecolor="yellow", lw=2))
|
|
|
+ ax = axes[0, 1]
|
|
|
+ ax.plot(np.arange(len(gy_prof)), gy_prof, lw=0.7, color="steelblue")
|
|
|
+ ax.axhline(limit, color="gray", ls="--", lw=0.8)
|
|
|
+ ax.axhline(-limit, color="gray", ls="--", lw=0.8)
|
|
|
+ for i in picked:
|
|
|
+ ax.plot(i, gy_prof[i], "o", ms=4, color="red")
|
|
|
+ for bd, c in ((dark, "orange"), (bright, "cyan")):
|
|
|
+ for bnd in bd:
|
|
|
+ ax.axvspan(bnd.y0-by0, bnd.y1-by0, color=c, alpha=0.25)
|
|
|
+ ax.set_title("2. Row Sobel profile (peaks=red dark=orange bright=cyan)", fontsize=9)
|
|
|
+ ax = axes[0, 2]
|
|
|
+ panel(ax, gray, "3. dark(orange) bright(cyan) box=BLUE bed=PINK")
|
|
|
+ for bnd in dark:
|
|
|
+ ax.plot([window[0], window[2]], [bnd.y0, bnd.y0], color="darkorange", lw=1)
|
|
|
+ for bnd in bright:
|
|
|
+ ax.plot([window[0], window[2]], [bnd.y0, bnd.y0], color="cyan", lw=1)
|
|
|
+ ax.plot([window[0], window[2]], [box.y1, box.y1], color="blue", lw=3)
|
|
|
+ if bed is not None:
|
|
|
+ ax.plot([window[0], window[2]], [bed.y0, bed.y0], color="magenta", lw=3)
|
|
|
+ ax = axes[0, 3]
|
|
|
+ za, zb = int(max(0, box.y1-60)), int(min(wh, (bed.y1 if bed else box.y1+80)+60))
|
|
|
+ panel(ax, gray[za:zb, window[0]:window[2]], "4. Gap zoom rows %d..%d" % (za, zb))
|
|
|
+ ax.plot([0, window[2]-window[0]], [box.y1-za, box.y1-za], color="blue", lw=2.5)
|
|
|
+ if bed is not None:
|
|
|
+ ax.plot([0, window[2]-window[0]], [bed.y0-za, bed.y0-za], color="magenta", lw=2.5)
|
|
|
+ ax = axes[1, 0]
|
|
|
+ panel(ax, gray, "5. Self-scale lines(green) best(RED) px/m=%s" %
|
|
|
+ ("None" if px_per_m is None else "%.0f" % px_per_m))
|
|
|
+ for line in scale_lines:
|
|
|
+ ax.plot([line[0], line[2]], [line[1], line[3]], color="lime", lw=0.8)
|
|
|
+ if scale_best:
|
|
|
+ ax.plot([scale_best[0], scale_best[2]], [scale_best[1], scale_best[3]], color="red", lw=2.5)
|
|
|
+ ax = axes[1, 1]
|
|
|
+ panel(ax, cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(gcrop), 50, 150),
|
|
|
+ "6. Below-ROI Canny")
|
|
|
+ ax = axes[1, 2]
|
|
|
+ panel(ax, gcrop, "7. vertical(cyan) post(green) cluster-x(red) posts=%d" % posts_n)
|
|
|
+ for s in structure["lines"]:
|
|
|
+ if abs(s["y1"]-s["y0"]) >= 1.8*abs(s["x1"]-s["x0"]):
|
|
|
+ cc = "lime" if (s["y1"]-s["y0"]) >= p.min_post_len_ratio*(ry1-ry0) else "cyan"
|
|
|
+ ax.plot([s["x0"]-rx0, s["x1"]-rx0], [s["y0"]-ry0, s["y1"]-ry0], color=cc, lw=1)
|
|
|
+ for x in _cluster_positions([(s["x0"]+s["x1"])*0.5 for s in structure["lines"]
|
|
|
+ if abs(s["y1"]-s["y0"]) >= 1.8*abs(s["x1"]-s["x0"])
|
|
|
+ and (s["y1"]-s["y0"]) >= p.min_post_len_ratio*(ry1-ry0)], 9.0*scale):
|
|
|
+ ax.axvline(x-rx0, color="red", ls=":", lw=1)
|
|
|
+ ax = axes[1, 3]
|
|
|
+ panel(ax, gcrop, "8. horizontal(orange) deck(MAGENTA) minlen=%.0f" % deck_min_len)
|
|
|
+ for s in structure["horizontal"]:
|
|
|
+ c, lw_ = ("magenta", 3) if s in deck_segs else ("orange", 1)
|
|
|
+ ax.plot([s["x0"]-rx0, s["x1"]-rx0], [s["y"]-ry0, s["y"]-ry0], color=c, lw=lw_)
|
|
|
+ ax = axes[2, 0]
|
|
|
+ panel(ax, gcrop, "9. blocks: ground=green structure=red (ground=%.2f)" % ground)
|
|
|
+ for (bxx, by, ex_, ey_, dens, is_g) in block_info:
|
|
|
+ ax.add_patch(Rectangle((bxx, by), ex_-bxx, ey_-by, fill=False,
|
|
|
+ edgecolor="lime" if is_g else "red", lw=1))
|
|
|
+ ax = axes[2, 1]
|
|
|
+ ha, hb = int(max(0, probe_top-120)), int(min(h, probe_top+180))
|
|
|
+ ax.imshow(gray0[ha:hb, int(0.15*w):int(0.85*w)], cmap="gray")
|
|
|
+ ax.set_title("10. Hoist probe_top=%.0f flag=%s" % (probe_top, hoist_flag), fontsize=9)
|
|
|
+ ax.axhline(probe_top-ha, color="yellow", lw=2)
|
|
|
+ ax.axis("off")
|
|
|
+ ax = axes[2, 2]
|
|
|
+ orig_rgb = cv2.cvtColor(cv2.resize(gray0, (ww, wh)) if scale < 1 else gray0, cv2.COLOR_GRAY2RGB)
|
|
|
+ panel(ax, orig_rgb, "11. Final overlay")
|
|
|
+ ax.add_patch(Rectangle((x0w, y0w), x1w-x0w, below_work[3]-y0w,
|
|
|
+ fill=False, edgecolor="yellow", lw=2))
|
|
|
+ ax.plot([0, ww], [box.y1, box.y1], color="blue", lw=2.5)
|
|
|
+ if bed is not None:
|
|
|
+ ax.plot([0, ww], [bed.y0, bed.y0], color="magenta", lw=2.5)
|
|
|
+ if scale_best:
|
|
|
+ ax.plot([scale_best[0], scale_best[2]], [scale_best[1], scale_best[3]], color="red", lw=2)
|
|
|
+ ax = axes[2, 3]
|
|
|
+ ax.axis("off")
|
|
|
+ ax.text(0.0, 0.98, "\n".join(card), fontsize=9, family="monospace", va="top")
|
|
|
+
|
|
|
+ plt.tight_layout(rect=[0, 0, 1, 0.96])
|
|
|
+ out_path = os.path.join(out_dir, os.path.splitext(fn)[0][:60] + "_steps.png")
|
|
|
+ fig.savefig(out_path, dpi=140)
|
|
|
+ print("saved", out_path)
|
|
|
+ print("size %dx%d scale=%.3f" % (w, h, scale))
|
|
|
+ print("box=%.1f..%.1f bed=%s gap=%s px/m=%s hoist=%s" %
|
|
|
+ (box.y0, box.y1, bed, gap_px, px_per_m, hoist_flag))
|
|
|
+ print("posts=%d cv=%s ground=%.2f opacity=%.2f deck=%s(%d segs) rect=%d diag=%d" %
|
|
|
+ (posts_n, structure["post_spacing_cv"], ground, opacity, deck_edge,
|
|
|
+ len(deck_segs), structure["rect_doors"], structure["diagonal_lines"]))
|
|
|
+ print("bed_strong=%s flat_strong=%s zero=%s" % (bed_ok, flat_ok, zero_ok))
|
|
|
+ print("cand=%d (%s) conf=%.2f hits=%.2f reason=%s" %
|
|
|
+ (state, STATE_NAME.get(state, "?"), conf, hits, reason))
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ raise SystemExit(main())
|