inference_webcam.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """
  2. Inference on webcams: Use a model on webcam input.
  3. Once launched, the script is in background collection mode.
  4. Press B to toggle between background capture mode and matting mode. The frame shown when B is pressed is used as background for matting.
  5. Press Q to exit.
  6. Example:
  7. python inference_webcam.py \
  8. --model-type mattingrefine \
  9. --model-backbone resnet50 \
  10. --model-checkpoint "PATH_TO_CHECKPOINT" \
  11. --resolution 1280 720
  12. """
  13. import argparse, os, shutil, time
  14. import cv2
  15. import torch
  16. from torch import nn
  17. from torch.utils.data import DataLoader
  18. from torchvision.transforms import Compose, ToTensor, Resize
  19. from torchvision.transforms.functional import to_pil_image
  20. from threading import Thread, Lock
  21. from tqdm import tqdm
  22. from PIL import Image
  23. from dataset import VideoDataset
  24. from model import MattingBase, MattingRefine
  25. # --------------- Arguments ---------------
  26. parser = argparse.ArgumentParser(description='Inference from web-cam')
  27. parser.add_argument('--model-type', type=str, required=True, choices=['mattingbase', 'mattingrefine'])
  28. parser.add_argument('--model-backbone', type=str, required=True, choices=['resnet101', 'resnet50', 'mobilenetv2'])
  29. parser.add_argument('--model-backbone-scale', type=float, default=0.25)
  30. parser.add_argument('--model-checkpoint', type=str, required=True)
  31. parser.add_argument('--model-refine-mode', type=str, default='sampling', choices=['full', 'sampling', 'thresholding'])
  32. parser.add_argument('--model-refine-sample-pixels', type=int, default=80_000)
  33. parser.add_argument('--model-refine-threshold', type=float, default=0.7)
  34. parser.add_argument('--hide-fps', action='store_true')
  35. parser.add_argument('--resolution', type=int, nargs=2, metavar=('width', 'height'), default=(1280, 720))
  36. args = parser.parse_args()
  37. # ----------- Utility classes -------------
  38. # A wrapper that reads data from cv2.VideoCapture in its own thread to optimize.
  39. # Use .read() in a tight loop to get the newest frame
  40. class Camera:
  41. def __init__(self, device_id=0, width=1280, height=720):
  42. self.capture = cv2.VideoCapture(device_id)
  43. self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)
  44. self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
  45. self.width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH))
  46. self.height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
  47. # self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 2)
  48. self.success_reading, self.frame = self.capture.read()
  49. self.read_lock = Lock()
  50. self.thread = Thread(target=self.__update, args=())
  51. self.thread.daemon = True
  52. self.thread.start()
  53. def __update(self):
  54. while self.success_reading:
  55. grabbed, frame = self.capture.read()
  56. with self.read_lock:
  57. self.success_reading = grabbed
  58. self.frame = frame
  59. def read(self):
  60. with self.read_lock:
  61. frame = self.frame.copy()
  62. return frame
  63. def __exit__(self, exec_type, exc_value, traceback):
  64. self.capture.release()
  65. # An FPS tracker that computes exponentialy moving average FPS
  66. class FPSTracker:
  67. def __init__(self, ratio=0.5):
  68. self._last_tick = None
  69. self._avg_fps = None
  70. self.ratio = ratio
  71. def tick(self):
  72. if self._last_tick is None:
  73. self._last_tick = time.time()
  74. return None
  75. t_new = time.time()
  76. fps_sample = 1.0 / (t_new - self._last_tick)
  77. self._avg_fps = self.ratio * fps_sample + (1 - self.ratio) * self._avg_fps if self._avg_fps is not None else fps_sample
  78. self._last_tick = t_new
  79. return self.get()
  80. def get(self):
  81. return self._avg_fps
  82. # Wrapper for playing a stream with cv2.imshow(). It can accept an image and return keypress info for basic interactivity.
  83. # It also tracks FPS and optionally overlays info onto the stream.
  84. class Displayer:
  85. def __init__(self, title, width=None, height=None, show_info=True):
  86. self.title, self.width, self.height = title, width, height
  87. self.show_info = show_info
  88. self.fps_tracker = FPSTracker()
  89. cv2.namedWindow(self.title, cv2.WINDOW_NORMAL)
  90. if width is not None and height is not None:
  91. cv2.resizeWindow(self.title, width, height)
  92. # Update the currently showing frame and return key press char code
  93. def step(self, image):
  94. fps_estimate = self.fps_tracker.tick()
  95. if self.show_info and fps_estimate is not None:
  96. message = f"{int(fps_estimate)} fps | {self.width}x{self.height}"
  97. cv2.putText(image, message, (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))
  98. cv2.imshow(self.title, image)
  99. return cv2.waitKey(1) & 0xFF
  100. # --------------- Main ---------------
  101. # Load model
  102. if args.model_type == 'mattingbase':
  103. model = MattingBase(args.model_backbone)
  104. if args.model_type == 'mattingrefine':
  105. model = MattingRefine(
  106. args.model_backbone,
  107. args.model_backbone_scale,
  108. args.model_refine_mode,
  109. args.model_refine_sample_pixels,
  110. args.model_refine_threshold)
  111. model = model.cuda().eval()
  112. model.load_state_dict(torch.load(args.model_checkpoint), strict=False)
  113. width, height = args.resolution
  114. cam = Camera(width=width, height=height)
  115. dsp = Displayer('MattingV2', cam.width, cam.height, show_info=(not args.hide_fps))
  116. def cv2_frame_to_cuda(frame):
  117. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  118. return ToTensor()(Image.fromarray(frame)).unsqueeze_(0).cuda()
  119. with torch.no_grad():
  120. while True:
  121. bgr = None
  122. while True: # grab bgr
  123. frame = cam.read()
  124. key = dsp.step(frame)
  125. if key == ord('b'):
  126. bgr = cv2_frame_to_cuda(cam.read())
  127. break
  128. elif key == ord('q'):
  129. exit()
  130. while True: # matting
  131. frame = cam.read()
  132. src = cv2_frame_to_cuda(frame)
  133. pha, fgr = model(src, bgr)[:2]
  134. res = pha * fgr + (1 - pha) * torch.ones_like(fgr)
  135. res = res.mul(255).byte().cpu().permute(0, 2, 3, 1).numpy()[0]
  136. res = cv2.cvtColor(res, cv2.COLOR_RGB2BGR)
  137. key = dsp.step(res)
  138. if key == ord('b'):
  139. break
  140. elif key == ord('q'):
  141. exit()