| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- """批量打印 detector.timed_infer() 输出并可视化检测框。
- 用法:
- python scripts/vis_detector_boxes_batch.py [image_dir] [backend] [config] [out_dir]
- """
- import os
- import sys
- import time
- import cv2
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- sys.path.insert(0, ROOT)
- from portcv.config import load_config
- from portcv.detect import build_detector, draw_boxes
- IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
- def iter_images(root: str):
- for name in sorted(os.listdir(root)):
- if name.lower().endswith(IMAGE_EXTS):
- yield os.path.join(root, name)
- def main() -> int:
- img_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
- ROOT, "dataset", "railcar-final-v1.v1i.yolov11", "test", "images"
- )
- backend = sys.argv[2] if len(sys.argv) > 2 else ""
- cfg_file = sys.argv[3] if len(sys.argv) > 3 else os.path.join(ROOT, "configs", "default.json")
- out_dir = sys.argv[4] if len(sys.argv) > 4 else os.path.join(ROOT, "runs", "detector_vis_batch")
- cfg = load_config(cfg_file)
- detector = build_detector(cfg, backend=backend)
- os.makedirs(out_dir, exist_ok=True)
- print("detector:", detector.describe())
- print("image_dir:", img_dir)
- print("out_dir:", out_dir)
- images = list(iter_images(img_dir))
- print("images count:", len(images))
- total_boxes = 0
- total_ms = 0.0
- failed = 0
- for idx, img_file in enumerate(images, 1):
- image = cv2.imread(img_file)
- if image is None:
- print("[%d/%d] READ_FAIL %s" % (idx, len(images), img_file))
- failed += 1
- continue
- h, w = image.shape[:2]
- boxes = detector.timed_infer(image)
- infer_ms = detector.infer_ms
- total_boxes += len(boxes)
- total_ms += infer_ms
- print("[%d/%d] %s size=%dx%d infer_ms=%.3f boxes=%d" % (
- idx, len(images), os.path.basename(img_file), w, h, infer_ms, len(boxes)
- ))
- for i, box in enumerate(boxes):
- print(" box[%d]: %s" % (i, box.to_dict()))
- vis = image.copy()
- roi_px = [(int(x * w), int(y * h)) for x, y in cfg.roi]
- draw_boxes(vis, boxes, roi=roi_px, texts=[
- "backend=%s" % detector.name,
- "boxes=%d infer_ms=%.2f" % (len(boxes), infer_ms),
- ])
- out_path = os.path.join(out_dir, os.path.splitext(os.path.basename(img_file))[0] + "_boxes.jpg")
- cv2.imwrite(out_path, vis)
- print("---- summary ----")
- print("images=%d failed=%d total_boxes=%d avg_infer_ms=%.3f" % (
- len(images), failed, total_boxes, total_ms / max(1, len(images) - failed)
- ))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|