当前位置: 首页 > 后端技术 > Python

使用神经网络轻松将照片转成梵高风格

时间:2023-03-26 11:15:56 Python

今天的文章,我们将实现风格转换效果。为了做到这一点,我们必须对卷积神经网络及其层的工作原理有更深入的了解。在本文结束时,您将能够创建和运行风格转换程序。什么是风格迁移在我们开始我们的风格迁移应用程序之前,让我们介绍一下我们正在努力实现的目标。给定输入图像和样式图像,我们可以计算具有原始内容和新样式的输出图像。就像下面的例子:波士顿的天际线和梵高的《星夜》相得益彰如何实现风格迁移1.我们将输入图像和风格图像调整为相同的形状。2.我们加载一个预训练的卷积神经网络(VGG16)。3.知道我们可以区分负责样式(基本形状、颜色等)的层和负责内容(图像特定特征)的层,我们可以将这些层分开以独立处理内容和样式。4.然后我们将我们的任务设置为我们想要最小化的优化问题:内容损失(输入和输出图像之间的距离——我们努力保持内容)风格损失(风格和输出图像之间的距离——我们努力应用新的风格)totalvariationloss(regularization-spatialsmoothnesstodenoisetheoutputimage)5.最后,我们使用L-BFGS算法设置梯度并优化。代码解释你可以在GitHub上找到风格转换项目的完整代码库:https://github.com/gsurma/sty...输入:#SanFranciscosan_francisco_image_path="https://www.economist.com/sites/default/files/images/print-edition/20180602_USP001_0.jpg"#输入可视化input_image=Image.open(BytesIO(requests.get(san_francisco_image_path).content))input_image=input_image.resize((IMAGE_WIDTH,IMAGE_HEIGHTim))input_image(input_image_path)input_image是下面的输入图像:Style:#WarsawbyTytusBrzozowski,http://t-b.pltytus_image_path="http://meetingbenches.com/wp-content/flagallery/tytus-brzozowski-polish-architect-and-watercolorist-a-fairy-tale-in-warsaw/tytus_brzozowski_13.jpg"#样式可视化.save(style_image_path)style_imagestyleimage:datapreprocessing:#数据归一化和从RGB到B的整形GRinput_image_array=np.asarray(input_image,dtype="float32")input_image_array=np.expand_dims(input_image_array,axis=0)input_image_array[:,:,:,0]-=IMAGENET_MEAN_RGB_VALUES[2]input_image_array[:,:,:,1]-=IMAGENET_MEAN_RGB_VALUES[1]input_image_array[:,:,:,2]-=IMAGENET_MEAN_RGB_VALUES[0]input_image_array=input_image_array[:,:,:,::-1]style_image_array=np.asarray(style_image,dtype="float32")style_image_array=np.expand_dims(style_image_array,轴=0)style_image_array[:,:,:,0]-=IMAGENET_MEAN_RGB_VALUES[2]style_image_array[:,:,:,1]-=IMAGENET_MEAN_RGB_VALUES[1]style_image_array[:,:,:,2]-=IMAGENET_MEAN_RGB_VALUES[0]style_image_array=style_image_array[:,:,:,::-1]网络模型:#Modelinput_image=backend.variable(input_image_array)style_image=backend.variable(style_image_array)combination_image=backend.placeholder((1,IMAGE_HEIGHT,IMAGE_SIZE,3))input_tensor=backend.concatenate([input_image,style_image,combination_image],axis=0)model=VGG16(input_tensor=input_tensor,include_top=False)运行程序后,我们得到如下结果:本文仅供学习,你在学习Python的道路上肯定会遇到困难,不要慌张,我这里有一套学习资料,包括40+本书图书,800+教学视频,涉及Python基础、爬虫、框架、数据分析、机器学习等,不怕你学不会!https://shimo.im/docs/JWCghr8...《Python学习资料》