vis_evidence_v2_steps.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. # 决策卡里有中文:用系统里带 CJK 的字体,避免变成方框(Windows 自带雅黑/黑体)。
  15. plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "DejaVu Sans"]
  16. plt.rcParams["axes.unicode_minus"] = False
  17. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  18. sys.path.insert(0, ROOT)
  19. from portcv.config import load_config
  20. from portcv.logic.evidence_v2 import (
  21. EvidenceV2, horizontal_bands, pick_box_and_bed, ground_like_ratio,
  22. detect_structure_v2, detect_hoist_high, _to_gray, _cluster_positions, _row_mean,
  23. )
  24. def main() -> int:
  25. if len(sys.argv) < 2:
  26. print(__doc__)
  27. return 2
  28. img_file = sys.argv[1]
  29. out_dir = sys.argv[2] if len(sys.argv) > 2 else os.path.join(ROOT, "runs", "yolo_vis_steps")
  30. os.makedirs(out_dir, exist_ok=True)
  31. cfg = load_config(os.path.join(ROOT, "configs", "edge-v2-front.json"))
  32. ev = EvidenceV2.from_config(cfg)
  33. p = ev.p
  34. fn = os.path.basename(img_file)
  35. image = cv2.imread(img_file)
  36. if image is None:
  37. print("cannot read", img_file)
  38. return 1
  39. # production 口径(含 P0-Q4 纹理顶/空车歧义、P0-Q6 无箱兜底、P0-Q7 空车弃权):
  40. # 脚本自身只复现“逐步证据”,结论一律以这里为准,避免两张卡口径不一致。
  41. prod = EvidenceV2.from_config(cfg).analyze(image, ts=0.0)
  42. gray0 = _to_gray(image)
  43. h, w = gray0.shape[:2]
  44. scale = min(1.0, float(p.work_width) / float(w))
  45. gray = cv2.resize(gray0, (int(round(w*scale)), int(round(h*scale))), interpolation=cv2.INTER_AREA) if scale < 1 else gray0.copy()
  46. wh, ww = gray.shape[:2]
  47. window = (int(p.window[0]*ww), int(p.window[1]*wh), int(p.window[2]*ww), int(p.window[3]*wh))
  48. max_h = max(6, int(p.band_max_h_ratio*wh))
  49. min_h_used = max(1, int(p.band_min_h*scale))
  50. bright, dark = horizontal_bands(gray, window, min_h=min_h_used, max_h=max_h)
  51. box_hint = max(80.0, 0.40*wh)
  52. box, bed = pick_box_and_bed(bright, dark, wh, box_bottom_max_ratio=p.box_bottom_max_ratio,
  53. bed_search_px=max(24.0, p.bed_search_ratio*box_hint))
  54. if box is None:
  55. # P0-Q6/Q7:罐箱箱底被车帮挡住时 production 会走“只看车体”兜底
  56. # (见 EdgeV2::analyze 的 box 缺失分支)。原脚本在这里直接 return,
  57. # 这张图就什么都看不到;补一个 4 宫格,把兜底路径也画出来。
  58. vy0, vy1 = max(0, window[1]), min(wh - 1, window[3])
  59. vx0 = max(0, int(round(p.body_x_margin_ratio * ww)))
  60. vx1 = min(ww - 1, int(round((1.0 - p.body_x_margin_ratio) * ww)))
  61. v_roi = (vx0, vy0, vx1, vy1)
  62. vst = detect_structure_v2(gray, v_roi, min_post_len_ratio=p.min_post_len_ratio,
  63. cluster_gap_px=9.0, scale=scale)
  64. vground, vblocks = ground_like_ratio(
  65. gray, v_roi, vst["lines"], block_px=p.ground_block_px,
  66. density_lo=p.ground_density_lo, density_hi=p.ground_density_hi)
  67. vposts = int(vst["post_count"])
  68. vpos = vst.get("post_positions") or []
  69. vspan = ((max(vpos) - min(vpos)) / max(1.0, float(vx1 - vx0))
  70. if len(vpos) >= 2 else 0.0)
  71. vdiag = int(vst["diagonal_lines"])
  72. vopacity = 1.0 - vground if vblocks > 0 else 0.0
  73. vwall = (p.body_min_posts <= vposts <= p.vehicle_max_posts
  74. and vspan >= p.vehicle_min_span_ratio
  75. and vopacity >= p.body_min_opacity
  76. and vdiag >= p.min_diagonal_braces)
  77. fig, axes = plt.subplots(2, 2, figsize=(16, 9))
  78. fig.suptitle("NO_BOX -> vehicle-only fallback (P0-Q6/Q7): %s" % fn, fontsize=11)
  79. ax = axes[0, 0]
  80. panel(ax, gray, "1. Input + window(green) + vehicle ROI(magenta)")
  81. ax.add_patch(Rectangle((window[0], window[1]), window[2] - window[0],
  82. window[3] - window[1], fill=False, edgecolor="lime", lw=1.5))
  83. ax.add_patch(Rectangle((vx0, vy0), vx1 - vx0, vy1 - vy0,
  84. fill=False, edgecolor="magenta", lw=2))
  85. ax = axes[0, 1]
  86. vcrop = gray[vy0:vy1, vx0:vx1]
  87. panel(ax, vcrop, "2. vehicle ROI: verticals(cyan) posts(green) diag(orange)")
  88. for s in vst["lines"]:
  89. dx, dy = abs(s["x1"] - s["x0"]), abs(s["y1"] - s["y0"])
  90. if dy >= 1.8 * max(1.0, dx):
  91. cc = "lime" if dy >= p.min_post_len_ratio * (vy1 - vy0) else "cyan"
  92. ax.plot([s["x0"] - vx0, s["x1"] - vx0], [s["y0"] - vy0, s["y1"] - vy0],
  93. color=cc, lw=1)
  94. elif 0.3 * dy <= dx <= 3.0 * dy:
  95. ax.plot([s["x0"] - vx0, s["x1"] - vx0], [s["y0"] - vy0, s["y1"] - vy0],
  96. color="orange", lw=1)
  97. ax = axes[1, 0]
  98. panel(ax, vcrop, "3. blocks: ground=green structure=red (ground=%.2f)" % vground)
  99. bpx = max(6, int(p.ground_block_px))
  100. for by in range(0, vcrop.shape[0], bpx):
  101. for bxx in range(0, vcrop.shape[1], bpx):
  102. ex_, ey_ = min(vcrop.shape[1], bxx + bpx), min(vcrop.shape[0], by + bpx)
  103. blk = vcrop[by:ey_, bxx:ex_].astype(np.float32)
  104. if blk.size == 0:
  105. continue
  106. dens = float((np.abs(cv2.Sobel(blk, cv2.CV_32F, 1, 0, ksize=3)) > 0).mean())
  107. is_g = p.ground_density_lo <= dens <= p.ground_density_hi
  108. ax.add_patch(Rectangle((bxx, by), ex_ - bxx, ey_ - by, fill=False,
  109. edgecolor="lime" if is_g else "red", lw=1))
  110. ax = axes[1, 1]
  111. ax.axis("off")
  112. card = [
  113. "NO_BOX -> VEHICLE-ONLY (P0-Q6)",
  114. "work %dx%d scale=%.3f" % (ww, wh, scale),
  115. "window=%s" % (str(window),),
  116. "vehicle ROI=%s h=%d" % (str(v_roi), vy1 - vy0),
  117. "posts=%d (body_min_posts=%d, vehicle_max_posts=%d)"
  118. % (vposts, p.body_min_posts, p.vehicle_max_posts),
  119. "span=%.2f (>=%.2f)" % (vspan, p.vehicle_min_span_ratio),
  120. "opacity=%.2f (>=%.2f)" % (vopacity, p.body_min_opacity),
  121. "diag=%d (>=%d)" % (vdiag, p.min_diagonal_braces),
  122. "",
  123. "wall_ok=%s" % vwall,
  124. "=> cand=%s" % ("1 BED(gondola)" if vwall else "255 UNKNOWN(no_box)"),
  125. "",
  126. "=== PROD analyze() [python ref; C++ is authoritative] ===",
  127. "[prod] candidate=%s abstain=%s class=%s" % (
  128. prod.state, prod.abstain_reason or "-", prod.class_reason or "-"),
  129. "",
  130. "注:空车(无箱)在 production 里统一 255(P0-Q7);",
  131. "此图只显示“只看车体”判据本身。",
  132. ]
  133. ax.text(0.0, 0.98, "\n".join(card), fontsize=9, va="top")
  134. plt.tight_layout(rect=[0, 0, 1, 0.95])
  135. out_path = os.path.join(out_dir, os.path.splitext(fn)[0][:60] + "_nobox_steps.png")
  136. fig.savefig(out_path, dpi=140)
  137. print("saved", out_path)
  138. print("NO_BOX(vehicle-only) posts=%d span=%.2f opacity=%.2f diag=%d wall_ok=%s"
  139. % (vposts, vspan, vopacity, vdiag, vwall))
  140. return 0
  141. by0 = window[1]
  142. crop = cv2.GaussianBlur(gray[window[1]:window[3], window[0]:window[2]].astype(np.float32), (3,3), 0)
  143. gy_prof = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
  144. mag = np.abs(gy_prof)
  145. limit = float(mag.mean()+0.9*mag.std())
  146. min_sep = max(2, int(round(min_h_used)))
  147. 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]]
  148. picked = []
  149. for i in sorted(cand, key=lambda j: mag[j], reverse=True):
  150. if all(abs(i-j)>=min_sep for j in picked):
  151. picked.append(i)
  152. picked.sort()
  153. px_per_m, vertical_run = ev._scale_from_vertical(gray, box, window, scale)
  154. sx0, sy0, sx1, _ = window
  155. scrop = gray[max(0,sy0):max(1,int(box.y0)), max(0,sx0):min(gray.shape[1],sx1)]
  156. scale_lines, scale_best, best_dy = [], None, 0.0
  157. if scrop.size:
  158. se = cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(scrop), 50, 150)
  159. sl = cv2.HoughLinesP(se, 1, math.pi/180.0, threshold=24,
  160. minLineLength=max(12, int(round(getattr(p, 'min_scale_px', 60)*scale))),
  161. maxLineGap=max(4, int(round(10*scale))))
  162. if sl is not None:
  163. for raw in np.asarray(sl).reshape(-1,4):
  164. xa, ya, xb, yb = (float(v) for v in raw)
  165. dx, dy = abs(xb-xa), abs(yb-ya)
  166. if dy >= 2.0*dx:
  167. scale_lines.append((xa+sx0, ya+sy0, xb+sx0, yb+sy0))
  168. if dy > best_dy:
  169. best_dy, scale_best = dy, (xa+sx0, ya+sy0, xb+sx0, yb+sy0)
  170. box_h_px = px_per_m*p.box_height_m if px_per_m is not None else None
  171. box_top = max(0.0, box.y1/max(scale,1e-6)-box_h_px) if box_h_px else None
  172. probe_top = float(box_top) if box_top is not None else max(0.0, box.y0/max(scale,1e-6)-0.35*h)
  173. hoist_flag, hoist_cues = detect_hoist_high(
  174. gray0, probe_top, dark_max=p.hoist_dark_max, band_frac=p.hoist_band_frac,
  175. line_ratio=p.hoist_line_ratio, dark_ratio=p.hoist_dark_ratio,
  176. bright_delta=p.hoist_bright_delta)
  177. est_h = max(60.0, box.y0-0.05*wh)
  178. start = max(2.0, p.below_start_ratio*est_h)
  179. min_below_h = p.below_min_height_px*max(scale,1e-6)
  180. if (wh-1)-box.y1 <= start+min_below_h:
  181. start = 2.0
  182. y0w = min(wh-2, int(math.ceil(box.y1+start)))
  183. below_h = max(min_below_h, min(p.below_height_ratio*est_h, 0.30*wh))
  184. y1w = min(wh-1, max(y0w+below_h, box.y1+0.10*est_h))
  185. x0w = max(0, int(0.05*ww))
  186. x1w = min(ww-1, int(0.95*ww))
  187. below_work = (x0w, y0w, x1w, max(y0w+8, int(y1w)))
  188. structure = detect_structure_v2(gray, below_work, min_post_len_ratio=p.min_post_len_ratio,
  189. cluster_gap_px=9.0, scale=scale)
  190. posts_n = int(structure["post_count"])
  191. ground, gblocks = ground_like_ratio(gray, below_work, structure["lines"],
  192. block_px=p.ground_block_px,
  193. density_lo=p.ground_density_lo,
  194. density_hi=p.ground_density_hi)
  195. opacity = max(0.0, min(1.0, 1.0-ground)) if gblocks > 0 else 0.0
  196. below_h_work = max(1.0, below_work[3]-below_work[1])
  197. deck_min_len = max(20.0, p.deck_min_len_ratio*0.55*ww)
  198. deck_segs = [s for s in structure["horizontal"]
  199. if box.y1-2.0 <= s["y"] <= box.y1+0.35*below_h_work
  200. and s["length"] >= deck_min_len]
  201. deck_edge = len(deck_segs) > 0
  202. gap_px = max(0.0, (bed.y0-box.y1)/max(scale,1e-6)) if bed is not None else None
  203. # 与 `EvidenceV2.analyze` 同口径补齐 P0-Q3/P0-Q6 的入参:
  204. # under_deck(车面下方暗带)、立柱间距(原图 px)、斜撑、跨度、ROI 高度。
  205. under_deck = False
  206. if bed is not None and (bed.y1 - bed.y0) > 0.0:
  207. band_mean = _row_mean(gray, window[0], window[2], bed.y0, bed.y1)
  208. probe_h = max(2, int(round(p.under_deck_min_h_ratio * wh)))
  209. search_h = max(probe_h + 1, int(round(p.under_deck_search_h_ratio * wh)))
  210. py0 = max(0, int(round(bed.y1)))
  211. py1 = min(wh - 1, py0 + search_h)
  212. darkest = min((_row_mean(gray, window[0], window[2], y, y + probe_h)
  213. for y in range(py0, max(py0 + 1, py1 - probe_h + 1))),
  214. default=None)
  215. under_deck = (darkest is not None
  216. and darkest <= band_mean - p.under_deck_dark_delta)
  217. deck_edge = bool(deck_edge and under_deck)
  218. post_pos = structure.get("post_positions") or []
  219. post_span_ratio = ((max(post_pos) - min(post_pos)) / max(1.0, float(ww))
  220. if len(post_pos) >= 2 else 0.0)
  221. post_spacing_px = (None if structure["post_spacing_median"] is None
  222. else float(structure["post_spacing_median"]) / max(scale, 1e-6))
  223. diagonal_braces = int(structure["diagonal_lines"])
  224. below_roi_h_px = float(below_h_work) / max(scale, 1e-6)
  225. state, conf, hits, reason = ev._classify(
  226. posts=posts_n, spacing_cv=structure["post_spacing_cv"], opacity=opacity,
  227. ground=ground, deck=deck_edge, wheels=0, gap_px=gap_px,
  228. motion_ok=True, view=p.view, under_deck=under_deck,
  229. post_spacing_px=post_spacing_px, diagonal_braces=diagonal_braces,
  230. post_span_ratio=post_span_ratio, below_roi_h_px=below_roi_h_px)
  231. rx0, ry0, rx1, ry1 = below_work
  232. gcrop = gray[ry0:ry1, rx0:rx1]
  233. gx = cv2.Sobel(gcrop, cv2.CV_32F, 1, 0, ksize=3)
  234. gyy = cv2.Sobel(gcrop, cv2.CV_32F, 0, 1, ksize=3)
  235. gmag = np.sqrt(gx*gx + gyy*gyy)
  236. hot = gmag > float(np.percentile(gmag, 60.0))
  237. bpx = max(6, int(p.ground_block_px))
  238. block_info = []
  239. for by in range(0, gcrop.shape[0], bpx):
  240. for bxx in range(0, gcrop.shape[1], bpx):
  241. ex_, ey_ = min(gcrop.shape[1], bxx+bpx), min(gcrop.shape[0], by+bpx)
  242. blk = hot[by:ey_, bxx:ex_]
  243. if blk.size == 0:
  244. continue
  245. dens = float(blk.mean())
  246. long_line = any(
  247. float(s["length"]) >= 0.6*bpx
  248. and rx0+bxx <= (s["x0"]+s["x1"])*0.5 <= rx0+ex_
  249. and ry0+by <= (s["y0"]+s["y1"])*0.5 <= ry0+ey_
  250. for s in structure["lines"])
  251. is_g = (not long_line) and p.ground_density_lo <= dens <= p.ground_density_hi
  252. block_info.append((bxx, by, ex_, ey_, dens, is_g))
  253. STATE_NAME = {0: "0 NOT_ON_TRAIN", 1: "1 BED(gondola)", 2: "2 FLATBED", 255: "255 UNKNOWN"}
  254. # 与 `_classify` 同口径(P0-Q3/Q4/Q6):间距 / 斜撑 / 跨度 / ROI 高度都要过。
  255. spacing_ok = (post_spacing_px is None or post_spacing_px <= 0.0
  256. or post_spacing_px >= p.min_post_spacing_px)
  257. span_ok = post_span_ratio >= p.min_post_span_ratio
  258. contact_bed = gap_px is None or float(gap_px) <= 1.0
  259. doors_ok = (not contact_bed) or diagonal_braces >= p.min_diagonal_braces
  260. post_array_regular = (posts_n < 8 or structure["post_spacing_cv"] is None
  261. or structure["post_spacing_cv"] <= 1.5)
  262. bed_evidence = (p.min_door_posts <= posts_n <= p.max_door_posts
  263. and opacity >= p.min_wall_opacity
  264. and (gap_px is None or gap_px <= p.max_bed_gap_px)
  265. and (structure["post_spacing_cv"] is None
  266. or structure["post_spacing_cv"] <= p.max_post_spacing_cv)
  267. and spacing_ok and doors_ok and span_ok and post_array_regular)
  268. bed_ok = bed_evidence and below_roi_h_px >= p.min_bed_roi_px
  269. flat_ok = (posts_n <= p.flat_max_door_posts and deck_edge and under_deck
  270. and (gap_px is None or gap_px <= p.max_flat_gap_px))
  271. zero_ok = (posts_n <= 1 and ground >= p.min_zero_ground_ratio and not deck_edge)
  272. card = [
  273. "DECISION CARD (work %dx%d scale=%.3f)" % (ww, wh, scale),
  274. "[bands] bright=%d dark=%d box_hint=%.0f" % (len(bright), len(dark), box_hint),
  275. "[box] y=%.1f..%.1f bed=%s" % (box.y0, box.y1,
  276. "None" if bed is None else "%.1f..%.1f" % (bed.y0, bed.y1)),
  277. "[gap_px] %s (<=40)" % ("None" if gap_px is None else "%.1f" % gap_px),
  278. "[scale] px/m=%s box_top=%s bestline=%s" % (
  279. "None" if px_per_m is None else "%.1f" % px_per_m,
  280. "None" if box_top is None else "%.0f" % box_top,
  281. "None" if scale_best is None else "%.0fpx" % best_dy),
  282. "[hoist] flag=%s lines=%s cables=%s" % (
  283. hoist_flag, hoist_cues.get("horizontal_lines"), hoist_cues.get("cables")),
  284. "[ROI] below=%s h=%.0f" % (str(below_work), below_h_work),
  285. "[struct] posts=%d vlines=%d hlines=%d rect=%d diag=%d" % (
  286. posts_n, structure["vertical_lines"], structure["horizontal_lines"],
  287. structure["rect_doors"], structure["diagonal_lines"]),
  288. "[spacing] median=%s cv=%s (<=6.0)" % (
  289. "None" if structure["post_spacing_median"] is None else "%.1f" % structure["post_spacing_median"],
  290. "None" if structure["post_spacing_cv"] is None else "%.2f" % structure["post_spacing_cv"]),
  291. "[texture] ground=%.2f opacity=%.2f" % (ground, opacity),
  292. "[deck] deck_edge=%s(under_deck=%s) minlen=%.0fpx segs=%d" % (
  293. deck_edge, under_deck, deck_min_len, len(deck_segs)),
  294. "[P0-Q3/Q6] spacing=%s(>=%.0f) span=%.2f(>=%.2f) diag=%d(>=%d) roi=%.0f(>=%d)" % (
  295. "None" if post_spacing_px is None else "%.0fpx" % post_spacing_px,
  296. p.min_post_spacing_px, post_span_ratio, p.min_post_span_ratio,
  297. diagonal_braces, p.min_diagonal_braces,
  298. below_roi_h_px, p.min_bed_roi_px),
  299. "",
  300. "=== PROD analyze() [python ref; C++ is authoritative] ===",
  301. "[prod] candidate=%s (%s)" % (
  302. prod.state, STATE_NAME.get(prod.state, "?")),
  303. "[prod] abstain=%s class=%s" % (
  304. prod.abstain_reason or "-", prod.class_reason or "-"),
  305. "[prod] body=(%d,%.2f,%.2f,%d) top=%.0f deck=%d under=%d" % (
  306. prod.body_posts, prod.body_span, prod.body_opacity, prod.body_diagonal,
  307. prod.texture_top_y or 0.0, int(bool(prod.deck_edge)),
  308. int(bool(prod.under_deck))),
  309. "", "bed_strong = %s" % ("YES" if bed_ok else "no"),
  310. "flat_strong= %s" % ("YES" if flat_ok else "no"),
  311. "zero = %s" % ("YES" if zero_ok else "no"), "",
  312. "=> cand=%d (%s) conf=%.2f hits=%.2f reason=%s" % (
  313. state, STATE_NAME.get(state, "?"), conf, hits, reason),
  314. ]
  315. fig, axes = plt.subplots(3, 4, figsize=(24, 15))
  316. fig.suptitle("Pipeline step visualization: %s" % fn[:70], fontsize=13)
  317. def panel(ax, img, title, cmap="gray"):
  318. ax.imshow(img, cmap=cmap)
  319. ax.set_title(title, fontsize=10)
  320. ax.axis("off")
  321. ax = axes[0, 0]
  322. panel(ax, gray, "1. Input + window(green) + below-ROI(yellow)")
  323. ax.add_patch(Rectangle((window[0], window[1]), window[2]-window[0], window[3]-window[1],
  324. fill=False, edgecolor="lime", lw=1.5))
  325. ax.add_patch(Rectangle((x0w, y0w), x1w-x0w, below_work[3]-y0w,
  326. fill=False, edgecolor="yellow", lw=2))
  327. ax = axes[0, 1]
  328. ax.plot(np.arange(len(gy_prof)), gy_prof, lw=0.7, color="steelblue")
  329. ax.axhline(limit, color="gray", ls="--", lw=0.8)
  330. ax.axhline(-limit, color="gray", ls="--", lw=0.8)
  331. for i in picked:
  332. ax.plot(i, gy_prof[i], "o", ms=4, color="red")
  333. for bd, c in ((dark, "orange"), (bright, "cyan")):
  334. for bnd in bd:
  335. ax.axvspan(bnd.y0-by0, bnd.y1-by0, color=c, alpha=0.25)
  336. ax.set_title("2. Row Sobel profile (peaks=red dark=orange bright=cyan)", fontsize=9)
  337. ax = axes[0, 2]
  338. panel(ax, gray, "3. dark(orange) bright(cyan) box=BLUE bed=PINK")
  339. for bnd in dark:
  340. ax.plot([window[0], window[2]], [bnd.y0, bnd.y0], color="darkorange", lw=1)
  341. for bnd in bright:
  342. ax.plot([window[0], window[2]], [bnd.y0, bnd.y0], color="cyan", lw=1)
  343. ax.plot([window[0], window[2]], [box.y1, box.y1], color="blue", lw=3)
  344. if bed is not None:
  345. ax.plot([window[0], window[2]], [bed.y0, bed.y0], color="magenta", lw=3)
  346. ax = axes[0, 3]
  347. za, zb = int(max(0, box.y1-60)), int(min(wh, (bed.y1 if bed else box.y1+80)+60))
  348. panel(ax, gray[za:zb, window[0]:window[2]], "4. Gap zoom rows %d..%d" % (za, zb))
  349. ax.plot([0, window[2]-window[0]], [box.y1-za, box.y1-za], color="blue", lw=2.5)
  350. if bed is not None:
  351. ax.plot([0, window[2]-window[0]], [bed.y0-za, bed.y0-za], color="magenta", lw=2.5)
  352. ax = axes[1, 0]
  353. panel(ax, gray, "5. Self-scale lines(green) best(RED) px/m=%s" %
  354. ("None" if px_per_m is None else "%.0f" % px_per_m))
  355. for line in scale_lines:
  356. ax.plot([line[0], line[2]], [line[1], line[3]], color="lime", lw=0.8)
  357. if scale_best:
  358. ax.plot([scale_best[0], scale_best[2]], [scale_best[1], scale_best[3]], color="red", lw=2.5)
  359. ax = axes[1, 1]
  360. panel(ax, cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(gcrop), 50, 150),
  361. "6. Below-ROI Canny")
  362. ax = axes[1, 2]
  363. panel(ax, gcrop, "7. vertical(cyan) post(green) cluster-x(red) posts=%d" % posts_n)
  364. for s in structure["lines"]:
  365. if abs(s["y1"]-s["y0"]) >= 1.8*abs(s["x1"]-s["x0"]):
  366. cc = "lime" if (s["y1"]-s["y0"]) >= p.min_post_len_ratio*(ry1-ry0) else "cyan"
  367. ax.plot([s["x0"]-rx0, s["x1"]-rx0], [s["y0"]-ry0, s["y1"]-ry0], color=cc, lw=1)
  368. for x in _cluster_positions([(s["x0"]+s["x1"])*0.5 for s in structure["lines"]
  369. if abs(s["y1"]-s["y0"]) >= 1.8*abs(s["x1"]-s["x0"])
  370. and (s["y1"]-s["y0"]) >= p.min_post_len_ratio*(ry1-ry0)], 9.0*scale):
  371. ax.axvline(x-rx0, color="red", ls=":", lw=1)
  372. ax = axes[1, 3]
  373. panel(ax, gcrop, "8. horizontal(orange) deck(MAGENTA) minlen=%.0f" % deck_min_len)
  374. for s in structure["horizontal"]:
  375. c, lw_ = ("magenta", 3) if s in deck_segs else ("orange", 1)
  376. ax.plot([s["x0"]-rx0, s["x1"]-rx0], [s["y"]-ry0, s["y"]-ry0], color=c, lw=lw_)
  377. ax = axes[2, 0]
  378. panel(ax, gcrop, "9. blocks: ground=green structure=red (ground=%.2f)" % ground)
  379. for (bxx, by, ex_, ey_, dens, is_g) in block_info:
  380. ax.add_patch(Rectangle((bxx, by), ex_-bxx, ey_-by, fill=False,
  381. edgecolor="lime" if is_g else "red", lw=1))
  382. ax = axes[2, 1]
  383. ha, hb = int(max(0, probe_top-120)), int(min(h, probe_top+180))
  384. ax.imshow(gray0[ha:hb, int(0.15*w):int(0.85*w)], cmap="gray")
  385. ax.set_title("10. Hoist probe_top=%.0f flag=%s" % (probe_top, hoist_flag), fontsize=9)
  386. ax.axhline(probe_top-ha, color="yellow", lw=2)
  387. ax.axis("off")
  388. ax = axes[2, 2]
  389. orig_rgb = cv2.cvtColor(cv2.resize(gray0, (ww, wh)) if scale < 1 else gray0, cv2.COLOR_GRAY2RGB)
  390. panel(ax, orig_rgb, "11. Final overlay")
  391. ax.add_patch(Rectangle((x0w, y0w), x1w-x0w, below_work[3]-y0w,
  392. fill=False, edgecolor="yellow", lw=2))
  393. ax.plot([0, ww], [box.y1, box.y1], color="blue", lw=2.5)
  394. if bed is not None:
  395. ax.plot([0, ww], [bed.y0, bed.y0], color="magenta", lw=2.5)
  396. if scale_best:
  397. ax.plot([scale_best[0], scale_best[2]], [scale_best[1], scale_best[3]], color="red", lw=2)
  398. ax = axes[2, 3]
  399. ax.axis("off")
  400. ax.text(0.0, 0.98, "\n".join(card), fontsize=9, va="top")
  401. plt.tight_layout(rect=[0, 0, 1, 0.96])
  402. out_path = os.path.join(out_dir, os.path.splitext(fn)[0][:60] + "_steps.png")
  403. fig.savefig(out_path, dpi=140)
  404. print("saved", out_path)
  405. print("size %dx%d scale=%.3f" % (w, h, scale))
  406. print("box=%.1f..%.1f bed=%s gap=%s px/m=%s hoist=%s" %
  407. (box.y0, box.y1, bed, gap_px, px_per_m, hoist_flag))
  408. print("posts=%d cv=%s ground=%.2f opacity=%.2f deck=%s(%d segs) rect=%d diag=%d" %
  409. (posts_n, structure["post_spacing_cv"], ground, opacity, deck_edge,
  410. len(deck_segs), structure["rect_doors"], structure["diagonal_lines"]))
  411. print("bed_strong=%s flat_strong=%s zero=%s" % (bed_ok, flat_ok, zero_ok))
  412. print("cand=%d (%s) conf=%.2f hits=%.2f reason=%s" %
  413. (state, STATE_NAME.get(state, "?"), conf, hits, reason))
  414. print("PROD candidate=%d abstain=%s class=%s body=(%d,%.2f,%.2f,%d) top=%.0f" % (
  415. prod.state, prod.abstain_reason or "-", prod.class_reason or "-",
  416. prod.body_posts, prod.body_span, prod.body_opacity, prod.body_diagonal,
  417. prod.texture_top_y or 0.0))
  418. return 0
  419. if __name__ == "__main__":
  420. raise SystemExit(main())