| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- """单图打印 detector.timed_infer() 输出并可视化检测框。
- 用法:
- python scripts/vis_detector_boxes.py [image] [backend] [config]
- """
- import os
- import sys
- 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
- def main() -> int:
- img_file = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
- ROOT, "dataset", "test_data", "32660093_235245226128_2.jpg"
- )
- 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")
- cfg = load_config(cfg_file)
- detector = build_detector(cfg, backend=backend)
- print("detector:", detector.describe())
- image = cv2.imread(img_file)
- if image is None:
- print("cannot read image:", img_file)
- return 1
- h, w = image.shape[:2]
- print("image:", img_file, "size:", w, "x", h)
- boxes = detector.timed_infer(image)
- print("infer_ms: %.3f" % detector.infer_ms)
- print("boxes count:", 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]
- texts = [
- "backend=%s" % detector.name,
- "infer_ms=%.2f boxes=%d" % (detector.infer_ms, len(boxes)),
- ]
- draw_boxes(vis, boxes, roi=roi_px, texts=texts)
- out_dir = os.path.join(ROOT, "runs", "detector_vis")
- os.makedirs(out_dir, exist_ok=True)
- out_path = os.path.join(
- out_dir, os.path.splitext(os.path.basename(img_file))[0] + "_boxes.jpg"
- )
- cv2.imwrite(out_path, vis)
- print("saved:", out_path)
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|