vis_detector_boxes.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """单图打印 detector.timed_infer() 输出并可视化检测框。
  2. 用法:
  3. python scripts/vis_detector_boxes.py [image] [backend] [config]
  4. """
  5. import os
  6. import sys
  7. import cv2
  8. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9. sys.path.insert(0, ROOT)
  10. from portcv.config import load_config
  11. from portcv.detect import build_detector, draw_boxes
  12. def main() -> int:
  13. img_file = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
  14. ROOT, "dataset", "test_data", "32660093_235245226128_2.jpg"
  15. )
  16. backend = sys.argv[2] if len(sys.argv) > 2 else ""
  17. cfg_file = sys.argv[3] if len(sys.argv) > 3 else os.path.join(ROOT, "configs", "default.json")
  18. cfg = load_config(cfg_file)
  19. detector = build_detector(cfg, backend=backend)
  20. print("detector:", detector.describe())
  21. image = cv2.imread(img_file)
  22. if image is None:
  23. print("cannot read image:", img_file)
  24. return 1
  25. h, w = image.shape[:2]
  26. print("image:", img_file, "size:", w, "x", h)
  27. boxes = detector.timed_infer(image)
  28. print("infer_ms: %.3f" % detector.infer_ms)
  29. print("boxes count:", len(boxes))
  30. for i, box in enumerate(boxes):
  31. print("box[%d]: %s" % (i, box.to_dict()))
  32. vis = image.copy()
  33. roi_px = [(int(x * w), int(y * h)) for x, y in cfg.roi]
  34. texts = [
  35. "backend=%s" % detector.name,
  36. "infer_ms=%.2f boxes=%d" % (detector.infer_ms, len(boxes)),
  37. ]
  38. draw_boxes(vis, boxes, roi=roi_px, texts=texts)
  39. out_dir = os.path.join(ROOT, "runs", "detector_vis")
  40. os.makedirs(out_dir, exist_ok=True)
  41. out_path = os.path.join(
  42. out_dir, os.path.splitext(os.path.basename(img_file))[0] + "_boxes.jpg"
  43. )
  44. cv2.imwrite(out_path, vis)
  45. print("saved:", out_path)
  46. return 0
  47. if __name__ == "__main__":
  48. raise SystemExit(main())