快速上手OpenCV实现图像风格化迁移
官微编辑部里看到一期赛博校园组图,但感觉变形扭曲看起来挺粗糙的,就想用OpenCV做一下风格化迁移
首先安装OpenCV
通过pip包管理器安装,非常便捷
python3 -m pip install opencv-python
风格化迁移代码
安装好OpenCV之后,需要一个DNN模块来实现风格化迁移
参考 https://github.com/opencv/opencv/blob/3.4.0/samples/dnn/fast_neural_style.py 中的代码
1 import cv2 as cv 2 import numpy as np 3 import argparse 4 5 parser = argparse.ArgumentParser( 6 description='This script is used to run style transfer models from ' 7 'https://github.com/jcjohnson/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 .t7 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 15 net = cv.dnn.readNetFromTorch(args.model) 16 17 if args.input: 18 cap = cv.VideoCapture(args.input) 19 else: 20 cap = cv.VideoCapture(0) 21 22 cv.namedWindow('Styled image', cv.WINDOW_NORMAL) 23 while cv.waitKey(1) < 0: 24 hasFrame, frame = cap.read() 25 if not hasFrame: 26 cv.waitKey() 27 break 28 29 inWidth = args.width if args.width != -1 else frame.shape[1] 30 inHeight = args.height if args.height != -1 else frame.shape[0] 31 inp = cv.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), 32 (103.939, 116.779, 123.68), swapRB=False, crop=False) 33 34 net.setInput(inp) 35 out = net.forward() 36 37 out = out.reshape(3, out.shape[2], out.shape[3]) 38 out[0] += 103.939 39 out[1] += 116.779 40 out[2] += 123.68 41 out /= 255 42 out = out.transpose(1, 2, 0) 43 44 t, _ = net.getPerfProfile() 45 freq = cv.getTickFrequency() / 1000 46 print t / freq, 'ms' 47 48 if args.median_filter: 49 out = cv.medianBlur(out, args.median_filter) 50 51 cv.imshow('Styled image', out)
调用的示例代码belike
python3 fast_neural_style.py --input input_aq.jpg --model xxx.t7
预训练风格化模型
在OpenCV中的参考项目 https://github.com/jcjohnson/fast-neural-style 中可以找到一些预训练好的风格化模型
按照readme的步骤配置Lua然后下载Model就行