vis_evidence_v2_steps.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. """单图逐步可视化 evidence_v2 判定链(12 宫格)。
  2. 用法:
  3. python scripts/vis_evidence_v2_steps.py <image> [<output_dir>]
  4. """
  5. import math
  6. import os
  7. import sys
  8. import cv2
  9. import numpy as np
  10. import matplotlib
  11. matplotlib.use("Agg")
  12. import matplotlib.pyplot as plt
  13. from matplotlib.patches import Rectangle
  14. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  15. sys.path.insert(0, ROOT)
  16. from portcv.config import load_config
  17. from portcv.logic.evidence_v2 import (
  18. EvidenceV2, horizontal_bands, pick_box_and_bed, ground_like_ratio,
  19. detect_structure_v2, detect_hoist_high, _to_gray, _cluster_positions,
  20. )
  21. def main() -> int:
  22. if len(sys.argv) < 2:
  23. print(__doc__)
  24. return 2
  25. img_file = sys.argv[1]
  26. out_dir = sys.argv[2] if len(sys.argv) > 2 else os.path.join(ROOT, "runs", "yolo_vis_steps")
  27. os.makedirs(out_dir, exist_ok=True)
  28. cfg = load_config(os.path.join(ROOT, "configs", "edge-v2-front.json"))
  29. ev = EvidenceV2.from_config(cfg)
  30. p = ev.p
  31. fn = os.path.basename(img_file)
  32. image = cv2.imread(img_file)
  33. if image is None:
  34. print("cannot read", img_file)
  35. return 1
  36. gray0 = _to_gray(image)
  37. h, w = gray0.shape[:2]
  38. scale = min(1.0, float(p.work_width) / float(w))
  39. gray = cv2.resize(gray0, (int(round(w*scale)), int(round(h*scale))), interpolation=cv2.INTER_AREA) if scale < 1 else gray0.copy()
  40. wh, ww = gray.shape[:2]
  41. window = (int(p.window[0]*ww), int(p.window[1]*wh), int(p.window[2]*ww), int(p.window[3]*wh))
  42. max_h = max(6, int(p.band_max_h_ratio*wh))
  43. min_h_used = max(1, int(p.band_min_h*scale))
  44. bright, dark = horizontal_bands(gray, window, min_h=min_h_used, max_h=max_h)
  45. box_hint = max(80.0, 0.40*wh)
  46. box, bed = pick_box_and_bed(bright, dark, wh, box_bottom_max_ratio=p.box_bottom_max_ratio,
  47. bed_search_px=max(24.0, p.bed_search_ratio*box_hint))
  48. if box is None:
  49. print("NO_BOX")
  50. return 0
  51. by0 = window[1]
  52. crop = cv2.GaussianBlur(gray[window[1]:window[3], window[0]:window[2]].astype(np.float32), (3,3), 0)
  53. gy_prof = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
  54. mag = np.abs(gy_prof)
  55. limit = float(mag.mean()+0.9*mag.std())
  56. min_sep = max(2, int(round(min_h_used)))
  57. 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]]
  58. picked = []
  59. for i in sorted(cand, key=lambda j: mag[j], reverse=True):
  60. if all(abs(i-j)>=min_sep for j in picked):
  61. picked.append(i)
  62. picked.sort()
  63. px_per_m, vertical_run = ev._scale_from_vertical(gray, box, window, scale)
  64. sx0, sy0, sx1, _ = window
  65. scrop = gray[max(0,sy0):max(1,int(box.y0)), max(0,sx0):min(gray.shape[1],sx1)]
  66. scale_lines, scale_best, best_dy = [], None, 0.0
  67. if scrop.size:
  68. se = cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(scrop), 50, 150)
  69. sl = cv2.HoughLinesP(se, 1, math.pi/180.0, threshold=24,
  70. minLineLength=max(12, int(round(getattr(p, 'min_scale_px', 60)*scale))),
  71. maxLineGap=max(4, int(round(10*scale))))
  72. if sl is not None:
  73. for raw in np.asarray(sl).reshape(-1,4):
  74. xa, ya, xb, yb = (float(v) for v in raw)
  75. dx, dy = abs(xb-xa), abs(yb-ya)
  76. if dy >= 2.0*dx:
  77. scale_lines.append((xa+sx0, ya+sy0, xb+sx0, yb+sy0))
  78. if dy > best_dy:
  79. best_dy, scale_best = dy, (xa+sx0, ya+sy0, xb+sx0, yb+sy0)
  80. box_h_px = px_per_m*p.box_height_m if px_per_m is not None else None
  81. box_top = max(0.0, box.y1/max(scale,1e-6)-box_h_px) if box_h_px else None
  82. probe_top = float(box_top) if box_top is not None else max(0.0, box.y0/max(scale,1e-6)-0.35*h)
  83. hoist_flag, hoist_cues = detect_hoist_high(
  84. gray0, probe_top, dark_max=p.hoist_dark_max, band_frac=p.hoist_band_frac,
  85. line_ratio=p.hoist_line_ratio, dark_ratio=p.hoist_dark_ratio,
  86. bright_delta=p.hoist_bright_delta)
  87. est_h = max(60.0, box.y0-0.05*wh)
  88. start = max(2.0, p.below_start_ratio*est_h)
  89. min_below_h = p.below_min_height_px*max(scale,1e-6)
  90. if (wh-1)-box.y1 <= start+min_below_h:
  91. start = 2.0
  92. y0w = min(wh-2, int(math.ceil(box.y1+start)))
  93. below_h = max(min_below_h, min(p.below_height_ratio*est_h, 0.30*wh))
  94. y1w = min(wh-1, max(y0w+below_h, box.y1+0.10*est_h))
  95. x0w = max(0, int(0.05*ww))
  96. x1w = min(ww-1, int(0.95*ww))
  97. below_work = (x0w, y0w, x1w, max(y0w+8, int(y1w)))
  98. structure = detect_structure_v2(gray, below_work, min_post_len_ratio=p.min_post_len_ratio,
  99. cluster_gap_px=9.0, scale=scale)
  100. posts_n = int(structure["post_count"])
  101. ground, gblocks = ground_like_ratio(gray, below_work, structure["lines"],
  102. block_px=p.ground_block_px,
  103. density_lo=p.ground_density_lo,
  104. density_hi=p.ground_density_hi)
  105. opacity = max(0.0, min(1.0, 1.0-ground)) if gblocks > 0 else 0.0
  106. below_h_work = max(1.0, below_work[3]-below_work[1])
  107. deck_min_len = max(20.0, p.deck_min_len_ratio*0.55*ww)
  108. deck_segs = [s for s in structure["horizontal"]
  109. if box.y1-2.0 <= s["y"] <= box.y1+0.35*below_h_work
  110. and s["length"] >= deck_min_len]
  111. deck_edge = len(deck_segs) > 0
  112. gap_px = max(0.0, (bed.y0-box.y1)/max(scale,1e-6)) if bed is not None else None
  113. state, conf, hits, reason = ev._classify(
  114. posts=posts_n, spacing_cv=structure["post_spacing_cv"], opacity=opacity,
  115. ground=ground, deck=deck_edge, wheels=0, gap_px=gap_px,
  116. motion_ok=True, view=p.view)
  117. rx0, ry0, rx1, ry1 = below_work
  118. gcrop = gray[ry0:ry1, rx0:rx1]
  119. gx = cv2.Sobel(gcrop, cv2.CV_32F, 1, 0, ksize=3)
  120. gyy = cv2.Sobel(gcrop, cv2.CV_32F, 0, 1, ksize=3)
  121. gmag = np.sqrt(gx*gx + gyy*gyy)
  122. hot = gmag > float(np.percentile(gmag, 60.0))
  123. bpx = max(6, int(p.ground_block_px))
  124. block_info = []
  125. for by in range(0, gcrop.shape[0], bpx):
  126. for bxx in range(0, gcrop.shape[1], bpx):
  127. ex_, ey_ = min(gcrop.shape[1], bxx+bpx), min(gcrop.shape[0], by+bpx)
  128. blk = hot[by:ey_, bxx:ex_]
  129. if blk.size == 0:
  130. continue
  131. dens = float(blk.mean())
  132. long_line = any(
  133. float(s["length"]) >= 0.6*bpx
  134. and rx0+bxx <= (s["x0"]+s["x1"])*0.5 <= rx0+ex_
  135. and ry0+by <= (s["y0"]+s["y1"])*0.5 <= ry0+ey_
  136. for s in structure["lines"])
  137. is_g = (not long_line) and p.ground_density_lo <= dens <= p.ground_density_hi
  138. block_info.append((bxx, by, ex_, ey_, dens, is_g))
  139. STATE_NAME = {0: "0 NOT_ON_TRAIN", 1: "1 BED(gondola)", 2: "2 FLATBED", 255: "255 UNKNOWN"}
  140. bed_ok = (p.min_door_posts <= posts_n <= p.max_door_posts
  141. and opacity >= p.min_wall_opacity
  142. and (gap_px is None or gap_px <= p.max_bed_gap_px)
  143. and (structure["post_spacing_cv"] is None
  144. or structure["post_spacing_cv"] <= p.max_post_spacing_cv))
  145. flat_ok = (posts_n <= p.flat_max_door_posts and deck_edge
  146. and (gap_px is None or gap_px <= p.max_flat_gap_px))
  147. zero_ok = (posts_n <= 1 and ground >= p.min_zero_ground_ratio and not deck_edge)
  148. card = [
  149. "DECISION CARD (work %dx%d scale=%.3f)" % (ww, wh, scale),
  150. "[bands] bright=%d dark=%d box_hint=%.0f" % (len(bright), len(dark), box_hint),
  151. "[box] y=%.1f..%.1f bed=%s" % (box.y0, box.y1,
  152. "None" if bed is None else "%.1f..%.1f" % (bed.y0, bed.y1)),
  153. "[gap_px] %s (<=40)" % ("None" if gap_px is None else "%.1f" % gap_px),
  154. "[scale] px/m=%s box_top=%s bestline=%s" % (
  155. "None" if px_per_m is None else "%.1f" % px_per_m,
  156. "None" if box_top is None else "%.0f" % box_top,
  157. "None" if scale_best is None else "%.0fpx" % best_dy),
  158. "[hoist] flag=%s lines=%s cables=%s" % (
  159. hoist_flag, hoist_cues.get("horizontal_lines"), hoist_cues.get("cables")),
  160. "[ROI] below=%s h=%.0f" % (str(below_work), below_h_work),
  161. "[struct] posts=%d vlines=%d hlines=%d rect=%d diag=%d" % (
  162. posts_n, structure["vertical_lines"], structure["horizontal_lines"],
  163. structure["rect_doors"], structure["diagonal_lines"]),
  164. "[spacing] median=%s cv=%s (<=6.0)" % (
  165. "None" if structure["post_spacing_median"] is None else "%.1f" % structure["post_spacing_median"],
  166. "None" if structure["post_spacing_cv"] is None else "%.2f" % structure["post_spacing_cv"]),
  167. "[texture] ground=%.2f opacity=%.2f" % (ground, opacity),
  168. "[deck] %s minlen=%.0fpx found=%d" % (deck_edge, deck_min_len, len(deck_segs)),
  169. "", "bed_strong = %s" % ("YES" if bed_ok else "no"),
  170. "flat_strong= %s" % ("YES" if flat_ok else "no"),
  171. "zero = %s" % ("YES" if zero_ok else "no"), "",
  172. "=> cand=%d (%s) conf=%.2f hits=%.2f reason=%s" % (
  173. state, STATE_NAME.get(state, "?"), conf, hits, reason),
  174. ]
  175. fig, axes = plt.subplots(3, 4, figsize=(24, 15))
  176. fig.suptitle("Pipeline step visualization: %s" % fn[:70], fontsize=13)
  177. def panel(ax, img, title, cmap="gray"):
  178. ax.imshow(img, cmap=cmap)
  179. ax.set_title(title, fontsize=10)
  180. ax.axis("off")
  181. ax = axes[0, 0]
  182. panel(ax, gray, "1. Input + window(green) + below-ROI(yellow)")
  183. ax.add_patch(Rectangle((window[0], window[1]), window[2]-window[0], window[3]-window[1],
  184. fill=False, edgecolor="lime", lw=1.5))
  185. ax.add_patch(Rectangle((x0w, y0w), x1w-x0w, below_work[3]-y0w,
  186. fill=False, edgecolor="yellow", lw=2))
  187. ax = axes[0, 1]
  188. ax.plot(np.arange(len(gy_prof)), gy_prof, lw=0.7, color="steelblue")
  189. ax.axhline(limit, color="gray", ls="--", lw=0.8)
  190. ax.axhline(-limit, color="gray", ls="--", lw=0.8)
  191. for i in picked:
  192. ax.plot(i, gy_prof[i], "o", ms=4, color="red")
  193. for bd, c in ((dark, "orange"), (bright, "cyan")):
  194. for bnd in bd:
  195. ax.axvspan(bnd.y0-by0, bnd.y1-by0, color=c, alpha=0.25)
  196. ax.set_title("2. Row Sobel profile (peaks=red dark=orange bright=cyan)", fontsize=9)
  197. ax = axes[0, 2]
  198. panel(ax, gray, "3. dark(orange) bright(cyan) box=BLUE bed=PINK")
  199. for bnd in dark:
  200. ax.plot([window[0], window[2]], [bnd.y0, bnd.y0], color="darkorange", lw=1)
  201. for bnd in bright:
  202. ax.plot([window[0], window[2]], [bnd.y0, bnd.y0], color="cyan", lw=1)
  203. ax.plot([window[0], window[2]], [box.y1, box.y1], color="blue", lw=3)
  204. if bed is not None:
  205. ax.plot([window[0], window[2]], [bed.y0, bed.y0], color="magenta", lw=3)
  206. ax = axes[0, 3]
  207. za, zb = int(max(0, box.y1-60)), int(min(wh, (bed.y1 if bed else box.y1+80)+60))
  208. panel(ax, gray[za:zb, window[0]:window[2]], "4. Gap zoom rows %d..%d" % (za, zb))
  209. ax.plot([0, window[2]-window[0]], [box.y1-za, box.y1-za], color="blue", lw=2.5)
  210. if bed is not None:
  211. ax.plot([0, window[2]-window[0]], [bed.y0-za, bed.y0-za], color="magenta", lw=2.5)
  212. ax = axes[1, 0]
  213. panel(ax, gray, "5. Self-scale lines(green) best(RED) px/m=%s" %
  214. ("None" if px_per_m is None else "%.0f" % px_per_m))
  215. for line in scale_lines:
  216. ax.plot([line[0], line[2]], [line[1], line[3]], color="lime", lw=0.8)
  217. if scale_best:
  218. ax.plot([scale_best[0], scale_best[2]], [scale_best[1], scale_best[3]], color="red", lw=2.5)
  219. ax = axes[1, 1]
  220. panel(ax, cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(gcrop), 50, 150),
  221. "6. Below-ROI Canny")
  222. ax = axes[1, 2]
  223. panel(ax, gcrop, "7. vertical(cyan) post(green) cluster-x(red) posts=%d" % posts_n)
  224. for s in structure["lines"]:
  225. if abs(s["y1"]-s["y0"]) >= 1.8*abs(s["x1"]-s["x0"]):
  226. cc = "lime" if (s["y1"]-s["y0"]) >= p.min_post_len_ratio*(ry1-ry0) else "cyan"
  227. ax.plot([s["x0"]-rx0, s["x1"]-rx0], [s["y0"]-ry0, s["y1"]-ry0], color=cc, lw=1)
  228. for x in _cluster_positions([(s["x0"]+s["x1"])*0.5 for s in structure["lines"]
  229. if abs(s["y1"]-s["y0"]) >= 1.8*abs(s["x1"]-s["x0"])
  230. and (s["y1"]-s["y0"]) >= p.min_post_len_ratio*(ry1-ry0)], 9.0*scale):
  231. ax.axvline(x-rx0, color="red", ls=":", lw=1)
  232. ax = axes[1, 3]
  233. panel(ax, gcrop, "8. horizontal(orange) deck(MAGENTA) minlen=%.0f" % deck_min_len)
  234. for s in structure["horizontal"]:
  235. c, lw_ = ("magenta", 3) if s in deck_segs else ("orange", 1)
  236. ax.plot([s["x0"]-rx0, s["x1"]-rx0], [s["y"]-ry0, s["y"]-ry0], color=c, lw=lw_)
  237. ax = axes[2, 0]
  238. panel(ax, gcrop, "9. blocks: ground=green structure=red (ground=%.2f)" % ground)
  239. for (bxx, by, ex_, ey_, dens, is_g) in block_info:
  240. ax.add_patch(Rectangle((bxx, by), ex_-bxx, ey_-by, fill=False,
  241. edgecolor="lime" if is_g else "red", lw=1))
  242. ax = axes[2, 1]
  243. ha, hb = int(max(0, probe_top-120)), int(min(h, probe_top+180))
  244. ax.imshow(gray0[ha:hb, int(0.15*w):int(0.85*w)], cmap="gray")
  245. ax.set_title("10. Hoist probe_top=%.0f flag=%s" % (probe_top, hoist_flag), fontsize=9)
  246. ax.axhline(probe_top-ha, color="yellow", lw=2)
  247. ax.axis("off")
  248. ax = axes[2, 2]
  249. orig_rgb = cv2.cvtColor(cv2.resize(gray0, (ww, wh)) if scale < 1 else gray0, cv2.COLOR_GRAY2RGB)
  250. panel(ax, orig_rgb, "11. Final overlay")
  251. ax.add_patch(Rectangle((x0w, y0w), x1w-x0w, below_work[3]-y0w,
  252. fill=False, edgecolor="yellow", lw=2))
  253. ax.plot([0, ww], [box.y1, box.y1], color="blue", lw=2.5)
  254. if bed is not None:
  255. ax.plot([0, ww], [bed.y0, bed.y0], color="magenta", lw=2.5)
  256. if scale_best:
  257. ax.plot([scale_best[0], scale_best[2]], [scale_best[1], scale_best[3]], color="red", lw=2)
  258. ax = axes[2, 3]
  259. ax.axis("off")
  260. ax.text(0.0, 0.98, "\n".join(card), fontsize=9, family="monospace", va="top")
  261. plt.tight_layout(rect=[0, 0, 1, 0.96])
  262. out_path = os.path.join(out_dir, os.path.splitext(fn)[0][:60] + "_steps.png")
  263. fig.savefig(out_path, dpi=140)
  264. print("saved", out_path)
  265. print("size %dx%d scale=%.3f" % (w, h, scale))
  266. print("box=%.1f..%.1f bed=%s gap=%s px/m=%s hoist=%s" %
  267. (box.y0, box.y1, bed, gap_px, px_per_m, hoist_flag))
  268. print("posts=%d cv=%s ground=%.2f opacity=%.2f deck=%s(%d segs) rect=%d diag=%d" %
  269. (posts_n, structure["post_spacing_cv"], ground, opacity, deck_edge,
  270. len(deck_segs), structure["rect_doors"], structure["diagonal_lines"]))
  271. print("bed_strong=%s flat_strong=%s zero=%s" % (bed_ok, flat_ok, zero_ok))
  272. print("cand=%d (%s) conf=%.2f hits=%.2f reason=%s" %
  273. (state, STATE_NAME.get(state, "?"), conf, hits, reason))
  274. return 0
  275. if __name__ == "__main__":
  276. raise SystemExit(main())