webcam_demo.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import cv2
  4. import mmcv
  5. import torch
  6. from mmdet.apis import inference_detector, init_detector
  7. from mmdet.registry import VISUALIZERS
  8. def parse_args():
  9. parser = argparse.ArgumentParser(description='MMDetection webcam demo')
  10. parser.add_argument('config', help='test config file path')
  11. parser.add_argument('checkpoint', help='checkpoint file')
  12. parser.add_argument(
  13. '--device', type=str, default='cuda:0', help='CPU/CUDA device option')
  14. parser.add_argument(
  15. '--camera-id', type=int, default=0, help='camera device id')
  16. parser.add_argument(
  17. '--score-thr', type=float, default=0.5, help='bbox score threshold')
  18. args = parser.parse_args()
  19. return args
  20. def main():
  21. args = parse_args()
  22. # build the model from a config file and a checkpoint file
  23. device = torch.device(args.device)
  24. model = init_detector(args.config, args.checkpoint, device=device)
  25. # init visualizer
  26. visualizer = VISUALIZERS.build(model.cfg.visualizer)
  27. # the dataset_meta is loaded from the checkpoint and
  28. # then pass to the model in init_detector
  29. visualizer.dataset_meta = model.dataset_meta
  30. camera = cv2.VideoCapture(args.camera_id)
  31. print('Press "Esc", "q" or "Q" to exit.')
  32. while True:
  33. ret_val, img = camera.read()
  34. result = inference_detector(model, img)
  35. img = mmcv.imconvert(img, 'bgr', 'rgb')
  36. visualizer.add_datasample(
  37. name='result',
  38. image=img,
  39. data_sample=result,
  40. draw_gt=False,
  41. pred_score_thr=args.score_thr,
  42. show=False)
  43. img = visualizer.get_image()
  44. img = mmcv.imconvert(img, 'bgr', 'rgb')
  45. cv2.imshow('result', img)
  46. ch = cv2.waitKey(1)
  47. if ch == 27 or ch == ord('q') or ch == ord('Q'):
  48. break
  49. if __name__ == '__main__':
  50. main()