fast_neural_style.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from __future__ import print_function
  2. import cv2 as cv
  3. import numpy as np
  4. import argparse
  5. parser = argparse.ArgumentParser(
  6. description='This script is used to run style transfer models from '
  7. 'https://github.com/onnx/models/tree/main/vision/style_transfer/fast_neural_style using OpenCV')
  8. parser.add_argument('--input', help='Path to image or video. Skip to capture frames from camera')
  9. parser.add_argument('--model', help='Path to .onnx model')
  10. parser.add_argument('--width', default=-1, type=int, help='Resize input to specific width.')
  11. parser.add_argument('--height', default=-1, type=int, help='Resize input to specific height.')
  12. parser.add_argument('--median_filter', default=0, type=int, help='Kernel size of postprocessing blurring.')
  13. args = parser.parse_args()
  14. net = cv.dnn.readNet(cv.samples.findFile(args.model))
  15. net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
  16. if args.input:
  17. cap = cv.VideoCapture(args.input)
  18. else:
  19. cap = cv.VideoCapture(0)
  20. cv.namedWindow('Styled image', cv.WINDOW_NORMAL)
  21. while cv.waitKey(1) < 0:
  22. hasFrame, frame = cap.read()
  23. if not hasFrame:
  24. cv.waitKey()
  25. break
  26. inWidth = args.width if args.width != -1 else frame.shape[1]
  27. inHeight = args.height if args.height != -1 else frame.shape[0]
  28. inp = cv.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight),
  29. swapRB=True, crop=False)
  30. net.setInput(inp)
  31. out = net.forward()
  32. out = out.reshape(3, out.shape[2], out.shape[3])
  33. out = out.transpose(1, 2, 0)
  34. t, _ = net.getPerfProfile()
  35. freq = cv.getTickFrequency() / 1000
  36. print(t / freq, 'ms')
  37. if args.median_filter:
  38. out = cv.medianBlur(out, args.median_filter)
  39. out = np.clip(out, 0, 255)
  40. out = out.astype(np.uint8)
  41. cv.imshow('Styled image', out)