Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/fast_neural_style.py
16337 views
1
from __future__ import print_function
2
import cv2 as cv
3
import numpy as np
4
import argparse
5
6
parser = argparse.ArgumentParser(
7
description='This script is used to run style transfer models from '
8
'https://github.com/jcjohnson/fast-neural-style using OpenCV')
9
parser.add_argument('--input', help='Path to image or video. Skip to capture frames from camera')
10
parser.add_argument('--model', help='Path to .t7 model')
11
parser.add_argument('--width', default=-1, type=int, help='Resize input to specific width.')
12
parser.add_argument('--height', default=-1, type=int, help='Resize input to specific height.')
13
parser.add_argument('--median_filter', default=0, type=int, help='Kernel size of postprocessing blurring.')
14
args = parser.parse_args()
15
16
net = cv.dnn.readNetFromTorch(args.model)
17
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV);
18
19
if args.input:
20
cap = cv.VideoCapture(args.input)
21
else:
22
cap = cv.VideoCapture(0)
23
24
cv.namedWindow('Styled image', cv.WINDOW_NORMAL)
25
while cv.waitKey(1) < 0:
26
hasFrame, frame = cap.read()
27
if not hasFrame:
28
cv.waitKey()
29
break
30
31
inWidth = args.width if args.width != -1 else frame.shape[1]
32
inHeight = args.height if args.height != -1 else frame.shape[0]
33
inp = cv.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight),
34
(103.939, 116.779, 123.68), swapRB=False, crop=False)
35
36
net.setInput(inp)
37
out = net.forward()
38
39
out = out.reshape(3, out.shape[2], out.shape[3])
40
out[0] += 103.939
41
out[1] += 116.779
42
out[2] += 123.68
43
out /= 255
44
out = out.transpose(1, 2, 0)
45
46
t, _ = net.getPerfProfile()
47
freq = cv.getTickFrequency() / 1000
48
print(t / freq, 'ms')
49
50
if args.median_filter:
51
out = cv.medianBlur(out, args.median_filter)
52
53
cv.imshow('Styled image', out)
54
55