首页

文章

python可以做哪些有趣的事

发布网友 发布时间:2022-03-03 16:22

我来回答

2个回答

热心网友 时间:2022-03-03 17:51

画画



在本地用keras搭建风格转移平台

1.相关依赖库的安装

# 命令行安装keras、h5py、tensorflow
pip3 install keras
pip3 install h5py
pip3 install tensorflow

如果tensorflowan命令行安装失败,可以在这里下载whl包Python Extension Packages for Windows(进入网址后ctrl+F输入tensorflow可以快速搜索)

2.配置运行环境

下载VGG16模型z 放入如下目录当中

3.代码编写

from __future__ import print_functionfrom keras.preprocessing.image import load_img, img_to_arrayfrom scipy.misc import imsaveimport numpy as npfrom scipy.optimize import fmin_l_bfgs_bimport timeimport argparsefrom keras.applications import vgg16from keras import backend as Kparser = argparse.ArgumentParser(description='Neural style transfer with Keras.')parser.add_argument('base_image_path', metavar='base', type=str,
help='Path to the image to transform.')parser.add_argument('style_reference_image_path', metavar='ref', type=str,
help='Path to the style reference image.')parser.add_argument('result_prefix', metavar='res_prefix', type=str,
help='Prefix for the saved results.')parser.add_argument('--iter', type=int, default=10, required=False,
help='Number of iterations to run.')parser.add_argument('--content_weight', type=float, default=0.025, required=False,
help='Content weight.')parser.add_argument('--style_weight', type=float, default=1.0, required=False,
help='Style weight.')parser.add_argument('--tv_weight', type=float, default=1.0, required=False,
help='Total Variation weight.')args = parser.parse_args()base_image_path = args.base_image_pathstyle_reference_image_path = args.style_reference_image_pathresult_prefix = args.result_prefixiterations = args.iter# these are the weights of the different loss componentstotal_variation_weight = args.tv_weightstyle_weight = args.style_weightcontent_weight = args.content_weight# dimensions of the generated picture.width, height = load_img(base_image_path).sizeimg_nrows = 400img_ncols = int(width * img_nrows / height)# util function to open, resize and format pictures into appropriate tensorsdef preprocess_image(image_path):
img = load_img(image_path, target_size=(img_nrows, img_ncols))
img = img_to_array(img)
img = np.expand_dims(img, axis=0)
img = vgg16.preprocess_input(img)
return img# util function to convert a tensor into a valid imagedef deprocess_image(x):
if K.image_data_format() == 'channels_first':
x = x.reshape((3, img_nrows, img_ncols))
x = x.transpose((1, 2, 0))
else:
x = x.reshape((img_nrows, img_ncols, 3))
# Remove zero-center by mean pixel
x[:, :, 0] += 103.939
x[:, :, 1] += 116.779
x[:, :, 2] += 123.68
# 'BGR'->'RGB'
x = x[:, :, ::-1]
x = np.clip(x, 0, 255).astype('uint8')
return x# get tensor representations of our imagesbase_image = K.variable(preprocess_image(base_image_path))style_reference_image = K.variable(preprocess_image(style_reference_image_path))# this will contain our generated imageif K.image_data_format() == 'channels_first':
combination_image = K.placeholder((1, 3, img_nrows, img_ncols))else:
combination_image = K.placeholder((1, img_nrows, img_ncols, 3))# combine the 3 images into a single Keras tensorinput_tensor = K.concatenate([base_image,
style_reference_image,
combination_image], axis=0)# build the VGG16 network with our 3 images as input# the model will be loaded with pre-trained ImageNet weightsmodel = vgg16.VGG16(input_tensor=input_tensor,
weights='imagenet', include_top=False)print('Model loaded.')# get the symbolic outputs of each "key" layer (we gave them unique names).outputs_dict = dict([(layer.name, layer.output) for layer in model.layers])# compute the neural style loss# first we need to define 4 util functions# the gram matrix of an image tensor (feature-wise outer proct)def gram_matrix(x):
assert K.ndim(x) == 3
if K.image_data_format() == 'channels_first':
features = K.batch_flatten(x)
else:
features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))
gram = K.dot(features, K.transpose(features))
return gram# the "style loss" is designed to maintain# the style of the reference image in the generated image.# It is based on the gram matrices (which capture style) of# feature maps from the style reference image# and from the generated imagedef style_loss(style, combination):
assert K.ndim(style) == 3
assert K.ndim(combination) == 3
S = gram_matrix(style)
C = gram_matrix(combination)
channels = 3
size = img_nrows * img_ncols
return K.sum(K.square(S - C)) / (4. * (channels ** 2) * (size ** 2))# an auxiliary loss function# designed to maintain the "content" of the# base image in the generated imagedef content_loss(base, combination):
return K.sum(K.square(combination - base))# the 3rd loss function, total variation loss,# designed to keep the generated image locally coherentdef total_variation_loss(x):
assert K.ndim(x) == 4
if K.image_data_format() == 'channels_first':
a = K.square(x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, 1:, :img_ncols - 1])
b = K.square(x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, :img_nrows - 1, 1:])
else:
a = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, 1:, :img_ncols - 1, :])
b = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, :img_nrows - 1, 1:, :])
return K.sum(K.pow(a + b, 1.25))# combine these loss functions into a single scalarloss = K.variable(0.)layer_features = outputs_dict['block4_conv2']base_image_features = layer_features[0, :, :, :]combination_features = layer_features[2, :, :, :]loss += content_weight * content_loss(base_image_features,
combination_features)feature_layers = ['block1_conv1', 'block2_conv1',
'block3_conv1', 'block4_conv1',
'block5_conv1']for layer_name in feature_layers:
layer_features = outputs_dict[layer_name]
style_reference_features = layer_features[1, :, :, :]
combination_features = layer_features[2, :, :, :]
sl = style_loss(style_reference_features, combination_features)
loss += (style_weight / len(feature_layers)) * slloss += total_variation_weight * total_variation_loss(combination_image)# get the gradients of the generated image wrt the lossgrads = K.gradients(loss, combination_image)outputs = [loss]if isinstance(grads, (list, tuple)):
outputs += gradselse:
outputs.append(grads)f_outputs = K.function([combination_image], outputs)def eval_loss_and_grads(x):
if K.image_data_format() == 'channels_first':
x = x.reshape((1, 3, img_nrows, img_ncols))
else:
x = x.reshape((1, img_nrows, img_ncols, 3))
outs = f_outputs([x])
loss_value = outs[0]
if len(outs[1:]) == 1:
grad_values = outs[1].flatten().astype('float64')
else:
grad_values = np.array(outs[1:]).flatten().astype('float64')
return loss_value, grad_values# this Evaluator class makes it possible# to compute loss and gradients in one pass# while retrieving them via two separate functions,# "loss" and "grads". This is done because scipy.optimize# requires separate functions for loss and gradients,# but computing them separately would be inefficient.class Evaluator(object):

def __init__(self):
self.loss_value = None
self.grads_values = None

def loss(self, x):
assert self.loss_value is None
loss_value, grad_values = eval_loss_and_grads(x)
self.loss_value = loss_value
self.grad_values = grad_values
return self.loss_value

def grads(self, x):
assert self.loss_value is not None
grad_values = np.copy(self.grad_values)
self.loss_value = None
self.grad_values = None
return grad_valuesevaluator = Evaluator()# run scipy-based optimization (L-BFGS) over the pixels of the generated image# so as to minimize the neural style lossif K.image_data_format() == 'channels_first':
x = np.random.uniform(0, 255, (1, 3, img_nrows, img_ncols)) - 128.else:
x = np.random.uniform(0, 255, (1, img_nrows, img_ncols, 3)) - 128.for i in range(iterations):
print('Start of iteration', i)
start_time = time.time()
x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(),
fprime=evaluator.grads, maxfun=20)
print('Current loss value:', min_val)
# save current generated image
img = deprocess_image(x.copy())
fname = result_prefix + '_at_iteration_%d.png' % i
imsave(fname, img)
end_time = time.time()
print('Image saved as', fname)print('Iteration %d completed in %ds' % (i, end_time - start_time))

复制上述代码保存为neural_style_transfer.py(随便命名)

4.运行

新建一个空文件夹,把上一步骤的文件neural_style_transfer.py放入这个空文件夹中。然后把相应的模板图片,待转化图片放入该文件当中。

python neural_style_transfer.py   你的待转化图片路径    模板图片路径   保存的生产图片路径加名称(注意不需要有.jpg等后缀)
python neural_style_transfer.py './me.jpg' './starry_night.jpg' './me_t'

迭代结果截图:

迭代过程对比

热心网友 时间:2022-03-03 19:09

Python是现在比较流行的编程语言,该语言功能强大、语法简单、容易上手受到了不少人的喜欢,同时Python适合零基础人员学习,也是初学者的首选;学习完Python编程之后可以做的事情有很多,比如说:人工智能、数据分析、web开发、爬虫、机器学习、科*算等。
如何分别真金和仿金首饰 怎样区分真金和仿金首饰呢 小学生新年晚会主持人的串词!!(不要太多)急 大大后天就需要了!!!_百度... 周年晚会策划公司 奥格瑞玛传送门大厅在哪 奥格瑞玛传送门大厅怎么走 锻炼颈椎的几个动作 水多久能结冰 冰能在多长时间内形成 请问水低于0度会结冰吗? 如何防止脱发严重 嘴唇上有黑印用蜜蜡和棉线去除了胡须 软柿子的热量 孕妇可以吃软柿子吗不是西红柿 脆柿子和软柿子的区别 脆柿子好还是软柿子好 软柿子可以多吃吗 “鱼悬洁白振清风”的出处是哪里 用大自然的声音评课好吗? 妇产科博士找超声科工作容易吗 怎能把微信6.2.0版本换回6.1.2版 微信群6.2.4怎么增加人数上限 微信6.2.2如何备份手机通讯录 电脑桌面图标不能放大? 有什么好用的识图软件 识图认人哪个软件最好 手机识图软件什么软件能识别图片位置 小米手机自动锁屏时间怎么修改 小米手机屏幕锁定时间设置教程 能举起100斤算大力吗 中医美容专业是什么 中医美容证有什么用 单声道音频什么意思(开启单声道音频有什么好处) 单声道音频是什么,有什么用处? 户口还未迁移到婆家 娘家户口怎么就没了呢 我结婚没有迁户口,现在娘家也没有怎么办 没领证生的孩子一般会判给谁 没领证生的孩子会判给谁 信用卡卡种有哪些 找一首古风歌曲 男声 低配电脑装w10还是w7流畅 电脑配置低装win7还是win10好 低配电脑适合装WIN7系统还是WIN10系统? ...500s-15isk这个联想笔记本的内存条尺寸是什么型号的有没有知道的... 越快越好.怎样减肥.而且胸部不缩水 请问徐闻县海安长途汽车客运站客服是多少? 过了平台期还会瘦吗 悦耳的意思悦耳的解释 重庆师范大学应用心理学专业的权威性如何? 打印机laserjetm1136mfp怎样设置无线打印 经典电影赏析之1:《精武英雄》 爆米花用的什么玉米 糯玉米哪个好 有机糯玉米的营养价值如何? 四大直辖市换帅原因 四大直辖市换帅为啥 本人14年考研,考CC,目前正在紧密复习中,可是9月中旬还得考会计初级,不知道怎么 学会python可以干哪些事情 MBA和CC哪个更难?考试单位是咋样的?需要报班吗? 学习Python都能做什么工作? 猎头如何打cc Python一般可以用来干什么呢? 我靠,今年怎么cc分数大家都考的这么高,怎么考的???? 对外经贸的CC很难考吗? python可以做哪些有趣的事情 考CC英语的精英班要考什么? cc是什么也是? cc考生是什么意思 艺术生考cc是不是太难了?? 骁龙888和麒麟980哪个处理器比较好? WORD文档里出现空白页怎么删除? 无线路由器如何安装设置????? 华为手机里的照片怎么导入电脑 美团商家怎样关闭顾客到店吃饭在网上评价 怎么运输螃蟹不容易死 螃蟹买回来怎么才能让它不死呀 用python能干什么有意思的事 python能做多少事情 python能做什么软件? python能做哪些好玩的事 华为手机风险管控中心在哪 华为风控管理中心怎么解除 在电脑上怎么做电子文档? 华为手机设备管理器在哪? 电子版文件怎么弄? 电子文档怎么制作呀! 华为手机设备管理器在哪 电脑怎么弄电子文档 电子文档手机上怎么做 华为手机的通知栏管理设置在哪 电子文档怎么弄呢?怎么放在WORD里呢? 华为手机的授权管理在哪里找? 手机怎么做电子文档 怎么做电子文档,怎么用qq发送 华为手机启动管理在哪里 word电子文件怎么做
声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com