livedemo_macwin.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import pyvirtualcam
  2. import numpy as np
  3. import cv2
  4. import torch
  5. from stylenet import StyleNetwork
  6. from torchvision import transforms as T
  7. net=StyleNetwork('./style_7.pth')
  8. for p in net.parameters():
  9. p.requires_grad=False
  10. device=torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
  11. net=net.eval().to(device) #use eval just for safety
  12. src=cv2.VideoCapture(1) #USB camera ID
  13. dummyframe=127*np.ones((720,1280,3),np.uint8)
  14. preprocess=T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
  15. #same normalization as that used in training data
  16. ret, frame=src.read()
  17. with pyvirtualcam.Camera(width=1280, height=720, fps=30) as vcam:
  18. print(f'Using virtual camera: {vcam.device} at {vcam.width} x {vcam.height}')
  19. while True:
  20. try:
  21. if ret:
  22. frame=cv2.resize(frame,(640,480))
  23. frame=(frame[:,:,::-1]/255.0).astype(np.float32) #convert BGR to RGB, convert to 0-1 range and cast to float32
  24. frame_tensor=torch.unsqueeze(torch.from_numpy(frame),0).permute(0,3,1,2)
  25. # add batch dimension and convert to NCHW format
  26. tensor_in = preprocess(frame_tensor) #normalize
  27. tensor_in=tensor_in.to(device) #send to GPU
  28. tensor_out = net(tensor_in) #stylized tensor
  29. tensor_out=torch.squeeze(tensor_out).permute(1,2,0) #remove batch dimension and convert to HWC (opencv format)
  30. stylized_frame=(255*(tensor_out.to('cpu').detach().numpy())).astype(np.uint8) #convert to 0-255 range and cast as uint8
  31. stylized_frame=cv2.resize(stylized_frame, (1280, 720))
  32. else:
  33. stylized_frame=dummyframe #if camera cannot be read, blank white image will be shown
  34. vcam.send(stylized_frame)
  35. #write to ffmpeg pipeline which in turn writes to virtual camera that can be accessed by zoom/skype/teams
  36. ret,frame=src.read()
  37. except KeyboardInterrupt:
  38. print('Received stop command')
  39. break
  40. src.release() #close ffmpeg pipeline and release camera