vis_detector_boxes_batch.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """批量打印 detector.timed_infer() 输出并可视化检测框。
  2. 用法:
  3. python scripts/vis_detector_boxes_batch.py [image_dir] [backend] [config] [out_dir]
  4. """
  5. import os
  6. import sys
  7. import time
  8. import cv2
  9. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  10. sys.path.insert(0, ROOT)
  11. from portcv.config import load_config
  12. from portcv.detect import build_detector, draw_boxes
  13. IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
  14. def iter_images(root: str):
  15. for name in sorted(os.listdir(root)):
  16. if name.lower().endswith(IMAGE_EXTS):
  17. yield os.path.join(root, name)
  18. def main() -> int:
  19. img_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
  20. ROOT, "dataset", "railcar-final-v1.v1i.yolov11", "test", "images"
  21. )
  22. backend = sys.argv[2] if len(sys.argv) > 2 else ""
  23. cfg_file = sys.argv[3] if len(sys.argv) > 3 else os.path.join(ROOT, "configs", "default.json")
  24. out_dir = sys.argv[4] if len(sys.argv) > 4 else os.path.join(ROOT, "runs", "detector_vis_batch")
  25. cfg = load_config(cfg_file)
  26. detector = build_detector(cfg, backend=backend)
  27. os.makedirs(out_dir, exist_ok=True)
  28. print("detector:", detector.describe())
  29. print("image_dir:", img_dir)
  30. print("out_dir:", out_dir)
  31. images = list(iter_images(img_dir))
  32. print("images count:", len(images))
  33. total_boxes = 0
  34. total_ms = 0.0
  35. failed = 0
  36. for idx, img_file in enumerate(images, 1):
  37. image = cv2.imread(img_file)
  38. if image is None:
  39. print("[%d/%d] READ_FAIL %s" % (idx, len(images), img_file))
  40. failed += 1
  41. continue
  42. h, w = image.shape[:2]
  43. boxes = detector.timed_infer(image)
  44. infer_ms = detector.infer_ms
  45. total_boxes += len(boxes)
  46. total_ms += infer_ms
  47. print("[%d/%d] %s size=%dx%d infer_ms=%.3f boxes=%d" % (
  48. idx, len(images), os.path.basename(img_file), w, h, infer_ms, len(boxes)
  49. ))
  50. for i, box in enumerate(boxes):
  51. print(" box[%d]: %s" % (i, box.to_dict()))
  52. vis = image.copy()
  53. roi_px = [(int(x * w), int(y * h)) for x, y in cfg.roi]
  54. draw_boxes(vis, boxes, roi=roi_px, texts=[
  55. "backend=%s" % detector.name,
  56. "boxes=%d infer_ms=%.2f" % (len(boxes), infer_ms),
  57. ])
  58. out_path = os.path.join(out_dir, os.path.splitext(os.path.basename(img_file))[0] + "_boxes.jpg")
  59. cv2.imwrite(out_path, vis)
  60. print("---- summary ----")
  61. print("images=%d failed=%d total_boxes=%d avg_infer_ms=%.3f" % (
  62. len(images), failed, total_boxes, total_ms / max(1, len(images) - failed)
  63. ))
  64. return 0
  65. if __name__ == "__main__":
  66. raise SystemExit(main())