vis_evidence_v2_steps.py 24 KB

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