inference_webcam_ts.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. from inference_webcam import Displayer, FPSTracker, Camera, cv2_frame_to_cuda
  30. # --------------- Arguments ---------------
  31. parser = argparse.ArgumentParser(description='Inference from web-cam')
  32. parser.add_argument('--model-type', type=str, required=True, choices=['mattingbase', 'mattingrefine'])
  33. parser.add_argument('--model-backbone', type=str, required=True, choices=['resnet101', 'resnet50', 'mobilenetv2'])
  34. parser.add_argument('--model-backbone-scale', type=float, default=0.25)
  35. parser.add_argument('--model-checkpoint', type=str, required=True)
  36. parser.add_argument('--model-refine-mode', type=str, default='sampling', choices=['full', 'sampling', 'thresholding'])
  37. parser.add_argument('--model-refine-sample-pixels', type=int, default=80_000)
  38. parser.add_argument('--model-refine-threshold', type=float, default=0.7)
  39. parser.add_argument('--hide-fps', action='store_true')
  40. parser.add_argument('--resolution', type=int, nargs=2, metavar=('width', 'height'), default=(1280, 720))
  41. parser.add_argument('--device-id', type=int, default=0)
  42. parser.add_argument('--background-image', type=str, default="")
  43. parser.add_argument('--fps-limit', type=int, default=1000)
  44. args = parser.parse_args()
  45. # --------------- Main ---------------
  46. model = torch.jit.load(args.model_checkpoint)
  47. model.backbone_scale = args.model_backbone_scale
  48. model.refine_mode = args.model_refine_mode
  49. model.refine_sample_pixels = args.model_refine_sample_pixels
  50. model.refine_threshold = args.model_refine_threshold
  51. datatype = torch.float16 if 'fp16' in args.model_checkpoint else torch.float32
  52. model = model.to(torch.device('cuda'))
  53. width, height = args.resolution
  54. cam = Camera(device_id=args.device_id,width=width, height=height)
  55. app = QApplication(['MattingV2'])
  56. dsp = Displayer('MattingV2', cam.width, cam.height, show_info=(not args.hide_fps))
  57. dsp.show()
  58. with torch.no_grad():
  59. while True:
  60. bgr = None
  61. while True: # grab bgr
  62. frame = cam.read()
  63. frameRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  64. key = dsp.step(frameRGB)
  65. if key == 'b':
  66. bgr = cv2_frame_to_cuda(frame, datatype)
  67. break
  68. elif key == 'w':
  69. cam.brighter()
  70. elif key == 's':
  71. cam.darker()
  72. elif key == 'q':
  73. exit()
  74. while True: # matting
  75. frame = cam.read()
  76. src = cv2_frame_to_cuda(frame, datatype)
  77. pha, fgr = model(src, bgr)[:2]
  78. res = pha
  79. res = res.mul(255).byte().cpu().permute(0, 2, 3, 1).numpy()[0]
  80. #res = cv2.cvtColor(res, cv2.COLOR_RGB2BGR)
  81. b_channel, g_channel, r_channel = cv2.split(frame)
  82. img_RGBA = cv2.merge((r_channel, g_channel, b_channel, res))
  83. key = dsp.step(img_RGBA)
  84. if key == 'b':
  85. break
  86. elif key == 'w':
  87. cam.brighter()
  88. elif key == 's':
  89. cam.darker()
  90. elif key == 'q':
  91. exit()