inference_webcam.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 numpy as np
  16. import torch
  17. from PyQt5 import QtGui, QtCore, uic
  18. from PyQt5 import QtWidgets
  19. from PyQt5.QtWidgets import QMainWindow, QApplication
  20. from torch import nn
  21. from torch.utils.data import DataLoader
  22. from torchvision.transforms import Compose, ToTensor, Resize
  23. from torchvision.transforms.functional import to_pil_image
  24. from threading import Thread, Lock, Condition
  25. from tqdm import tqdm
  26. from PIL import Image, ImageTk
  27. from dataset import VideoDataset
  28. from model import MattingBase, MattingRefine
  29. torch.backends.cudnn.benchmark = True
  30. # --------------- Arguments ---------------
  31. if __name__ == "__main__":
  32. parser = argparse.ArgumentParser(description='Inference from web-cam')
  33. parser.add_argument('--model-type', type=str, required=True, choices=['mattingbase', 'mattingrefine'])
  34. parser.add_argument('--model-backbone', type=str, required=True, choices=['resnet101', 'resnet50', 'mobilenetv2'])
  35. parser.add_argument('--model-backbone-scale', type=float, default=0.25)
  36. parser.add_argument('--model-checkpoint', type=str, required=True)
  37. parser.add_argument('--model-refine-mode', type=str, default='sampling', choices=['full', 'sampling', 'thresholding'])
  38. parser.add_argument('--model-refine-sample-pixels', type=int, default=80_000)
  39. parser.add_argument('--model-refine-threshold', type=float, default=0.7)
  40. parser.add_argument('--hide-fps', action='store_true')
  41. parser.add_argument('--resolution', type=int, nargs=2, metavar=('width', 'height'), default=(1280, 720))
  42. parser.add_argument('--device-id', type=int, default=0)
  43. args = parser.parse_args()
  44. # ----------- Utility classes -------------
  45. # A wrapper that reads data from cv2.VideoCapture in its own thread to optimize.
  46. # Use .read() in a tight loop to get the newest frame
  47. class Camera:
  48. def __init__(self, device_id=0, width=1280, height=720):
  49. self.capture = cv2.VideoCapture(device_id)
  50. self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)
  51. self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
  52. self.width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH))
  53. self.height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
  54. # self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 2)
  55. self.exposure = self.capture.get(cv2.CAP_PROP_EXPOSURE)
  56. self.capture.set(cv2.CAP_PROP_BACKLIGHT, 0)
  57. self.capture.set(cv2.CAP_PROP_EXPOSURE,self.exposure)
  58. self.frameAvailable = False
  59. self.success_reading, self.frame = self.capture.read()
  60. self.cv = Condition()
  61. self.thread = Thread(target=self.__update, args=())
  62. self.thread.daemon = True
  63. self.thread.start()
  64. def __update(self):
  65. while self.success_reading:
  66. grabbed, frame = self.capture.read()
  67. with self.cv:
  68. self.success_reading = grabbed
  69. self.frame = frame
  70. self.frameAvailable = True
  71. self.cv.notify()
  72. def brighter(self):
  73. if self.exposure < -2:
  74. self.exposure += 1
  75. self.capture.set(cv2.CAP_PROP_EXPOSURE,self.exposure)
  76. print(self.exposure)
  77. def darker(self):
  78. if self.exposure > -12:
  79. self.exposure -= 1
  80. self.capture.set(cv2.CAP_PROP_EXPOSURE,self.exposure)
  81. print(self.exposure)
  82. def read(self):
  83. with self.cv:
  84. self.cv.wait_for(lambda: self.frameAvailable)
  85. frame = self.frame.copy()
  86. self.frameAvailable = False
  87. return frame
  88. def __exit__(self, exec_type, exc_value, traceback):
  89. self.capture.release()
  90. # An FPS tracker that computes exponentialy moving average FPS
  91. class FPSTracker:
  92. def __init__(self, ratio=0.5):
  93. self._last_tick = None
  94. self._avg_fps = None
  95. self.ratio = ratio
  96. def tick(self):
  97. if self._last_tick is None:
  98. self._last_tick = time.time()
  99. return None
  100. t_new = time.time()
  101. fps_sample = 1.0 / (t_new - self._last_tick)
  102. self._avg_fps = self.ratio * fps_sample + (1 - self.ratio) * self._avg_fps if self._avg_fps is not None else fps_sample
  103. self._last_tick = t_new
  104. return self.get()
  105. def get(self):
  106. return self._avg_fps
  107. # Wrapper for playing a stream with cv2.imshow(). It can accept an image and return keypress info for basic interactivity.
  108. # It also tracks FPS and optionally overlays info onto the stream.
  109. class Displayer(QMainWindow):
  110. def __init__(self, title, width, height, show_info=True):
  111. self.width, self.height = width, height
  112. self.show_info = show_info
  113. self.fps_tracker = FPSTracker()
  114. QMainWindow.__init__(self)
  115. self.setFixedSize(width, height)
  116. self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
  117. self.image_label = QtWidgets.QLabel(self)
  118. self.image_label.resize(width, height)
  119. self.key = None
  120. def keyPressEvent(self, event):
  121. self.key = event.text()
  122. def closeEvent(self, event):
  123. self.key = 'q'
  124. # Update the currently showing frame and return key press char code
  125. def step(self, image):
  126. fps_estimate = self.fps_tracker.tick()
  127. if self.show_info and fps_estimate is not None:
  128. message = f"{int(fps_estimate)} fps | {self.width}x{self.height}"
  129. cv2.putText(image, message, (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))
  130. pix = self.convert_cv_qt(image)
  131. self.image_label.setPixmap(pix)
  132. QApplication.processEvents()
  133. key = self.key
  134. self.key = None
  135. return key
  136. def convert_cv_qt(self, cv_img):
  137. """Convert from an opencv image to QPixmap"""
  138. h, w, ch = cv_img.shape
  139. bytes_per_line = ch * w
  140. if ch == 3:
  141. convert_to_Qt_format = QtGui.QImage(cv_img.data, w, h, bytes_per_line, QtGui.QImage.Format_RGB888)
  142. elif ch == 4:
  143. convert_to_Qt_format = QtGui.QImage(cv_img.data, w, h, bytes_per_line, QtGui.QImage.Format_RGBA8888)
  144. return QtGui.QPixmap.fromImage(convert_to_Qt_format)
  145. def cv2_frame_to_cuda(frame, datatype = torch.float32):
  146. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  147. return torch.as_tensor(frame, device=torch.device("cuda")).type(datatype).unsqueeze(0).permute(0, 3, 1, 2)/255
  148. # --------------- Main ---------------
  149. if __name__ == "__main__":
  150. # Load model
  151. if args.model_type == 'mattingbase':
  152. model = MattingBase(args.model_backbone)
  153. if args.model_type == 'mattingrefine':
  154. model = MattingRefine(
  155. args.model_backbone,
  156. args.model_backbone_scale,
  157. args.model_refine_mode,
  158. args.model_refine_sample_pixels,
  159. args.model_refine_threshold)
  160. model = model.cuda().eval()
  161. model.load_state_dict(torch.load(args.model_checkpoint), strict=False)
  162. datatype = torch.float16 if 'fp16' in args.model_checkpoint else torch.float32
  163. width, height = args.resolution
  164. cam = Camera(device_id=args.device_id, width=width, height=height)
  165. app = QApplication(['MattingV2'])
  166. dsp = Displayer('MattingV2', cam.width, cam.height, show_info=(not args.hide_fps))
  167. dsp.show()
  168. with torch.no_grad():
  169. while True:
  170. bgr = None
  171. while True: # grab bgr
  172. frame = cam.read()
  173. frameRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  174. key = dsp.step(frameRGB)
  175. if key == 'b':
  176. bgr = cv2_frame_to_cuda(frame, datatype)
  177. break
  178. elif key == 'w':
  179. cam.brighter()
  180. elif key == 's':
  181. cam.darker()
  182. elif key == 'q':
  183. exit()
  184. while True: # matting
  185. frame = cam.read()
  186. src = cv2_frame_to_cuda(frame, datatype)
  187. pha, fgr = model(src, bgr)[:2]
  188. res = pha * fgr + (1 - pha) * torch.ones_like(fgr)
  189. res = res.mul(255).byte().cpu().permute(0, 2, 3, 1).numpy()[0]
  190. key = dsp.step(res.copy())
  191. if key == 'b':
  192. break
  193. elif key == 'w':
  194. cam.brighter()
  195. elif key == 's':
  196. cam.darker()
  197. elif key == 'q':
  198. exit()