在本学期结尾,潇小白与小鉴,小强,小鸣,小灿,小哲六个人一起组成了一个项目组花费了一周的时间做成了这个项目,在这里与大家分享。

-- coding: utf-8 --

@Time : 2018/5/22 14:31

@Author : Sun

@File : Final.py

from future import print_function
import time
import numpy as np
from keras.preprocessing.image import load_img, img_to_array
from scipy.misc import imsave
from scipy.optimize import fmin_l_bfgs_b
from keras.applications import vgg16
from keras import backend as K

def Change(base_image_path,style_reference_image_path,result_prefix,iterations):
# 不同损耗成分的权重
total_variation_weight = 1.0
style_weight = 1.0
content_weight = 0.025

# 计算求出迭代得到的图片的长和宽
width, height = load_img(base_image_path).size
img_nrows = 400
img_ncols = int(width * img_nrows / height)# 调整图片大小并将其格式化成合适的张量
def 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)  # 通过vgg16获取数据集特征return img# 将张量转换为有效图像
def deprocess_image(x):# channels_first 维度顺序if K.image_data_format() == 'channels_first':x = x.reshape((3, img_nrows, img_ncols))x = x.transpose((1, 2, 0))# channels_last 维度顺序else:x = x.reshape((img_nrows, img_ncols, 3))# 用平均像素去除零中心x[:, :, 0] += 103.939x[:, :, 1] += 116.779x[:, :, 2] += 123.68# BGR 模式 -> RGB 模式x = x[:, :, ::-1]x = np.clip(x, 0, 255).astype('uint8')return x# 得到源图像的张量表示
base_image = K.variable(preprocess_image(base_image_path))  # 源图像的张量表示
style_reference_image = K.variable(preprocess_image(style_reference_image_path))  # 风格图像的张量表示# 迭代图像
# channels_first 维度顺序方式
if K.image_data_format() == 'channels_first':combination_image = K.placeholder((1, 3, img_nrows, img_ncols))
# channels_last 维度顺序方式
else:combination_image = K.placeholder((1, img_nrows, img_ncols, 3))# 将三个图像合并成一个Keras张量
input_tensor = K.concatenate([base_image, style_reference_image, combination_image], axis=0)# 以base_image, style_reference_image, combination_image为输入构建VGG16网络
model = vgg16.VGG16(input_tensor=input_tensor,weights='imagenet', include_top=False)  # 模型加载预先训练的图像权重
print('模型已加载')outputs_dict = dict([(layer.name, layer.output) for layer in model.layers])  # 获取每个“键”层的符号输出# 图像张量的克矩阵
def gram_matrix(x):assert K.ndim(x) == 3# channels_first 维度顺序if K.image_data_format() == 'channels_first':features = K.batch_flatten(x)# channels_last 维度顺序else:features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))gram = K.dot(features, K.transpose(features))return gram# 风格损失
# 基于从样式引用图像和生成的图像中获取特征映射的gram矩阵
def 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_ncolsreturn K.sum(K.square(S - C)) / (4. * (channels ** 2) * (size ** 2))# 内容损失
# 用于维护生成图像中基本图像的“内容
def content_loss(base, combination):return K.sum(K.square(combination - base))# 总变异损失
# 保持生成的图像局部一致
def total_variation_loss(x):assert K.ndim(x) == 4# channels_first 维度顺序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:])# channels_last 维度顺序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))# 将上述三个损失函数的结果合并为单个标量
loss = 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)) * sl
loss += total_variation_weight * total_variation_loss(combination_image)# 获取生成图像的梯度损失
grads = K.gradients(loss, combination_image)outputs = [loss]
if isinstance(grads, (list, tuple)):outputs += grads
else:outputs.append(grads)f_outputs = K.function([combination_image], outputs)def eval_loss_and_grads(x):# channels_first 维度顺序if K.image_data_format() == 'channels_first':x = x.reshape((1, 3, img_nrows, img_ncols))# channels_last 维度顺序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# 求值类,计算传递损失和梯度
class Evaluator(object):def __init__(self):self.loss_value = Noneself.grads_values = Nonedef loss(self, x):assert self.loss_value is Noneloss_value, grad_values = eval_loss_and_grads(x)self.loss_value = loss_valueself.grad_values = grad_valuesreturn self.loss_valuedef grads(self, x):assert self.loss_value is not Nonegrad_values = np.copy(self.grad_values)self.loss_value = Noneself.grad_values = Nonereturn grad_valuesevaluator = Evaluator()  # 新建对象# 在生成图像的像素上运行基于SCIPI的优化(L-BFGS),以减少损失
# channels_first 维度顺序
if K.image_data_format() == 'channels_first':x = np.random.uniform(0, 255, (1, 3, img_nrows, img_ncols)) - 128.
# channels_last 维度顺序
else:x = np.random.uniform(0, 255, (1, img_nrows, img_ncols, 3)) - 128.for i in range(iterations):print('开始第%d次迭代'  %(i+1))start_time = time.time()x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(),fprime=evaluator.grads, maxfun=20)img = deprocess_image(x.copy())fname = result_prefix + '_at_iteration_%d.png' % (i+1)# 保存最后一次迭代得到的图像if(i+1 == iterations):imsave(fname, img)end_time = time.time()print('Iteration %d completed in %ds' % (i+1, end_time - start_time))
  • from tkinter import *
    from tkinter import ttk
    from PIL import Image,ImageTk
    import win32ui
    from Final import Change

‘’‘图形化界面’’’
class Window(Frame):
def init(self, master=None):
Frame.init(self, master)
self.master = master
self.init_window()

def init_window(self):self.master.title("图像风格渲染器")self.pack(fill=BOTH, expand=1)# 实例化一个Menu对象,这个在主窗体添加一个菜单menu = Menu(self.master)self.master.config(menu=menu)# 创建“文件”菜单,下面有“保存”和“退出”两个子菜单file = Menu(menu)file.add_command(label='保存')file.add_command(label='退出', command=self.client_exit)menu.add_cascade(label='文件', menu=file)# 创建“帮助”菜单,下面有“使用帮助”和“版权”两个子菜单forhelp = Menu(menu)forhelp.add_command(label='使用帮助')forhelp.add_command(label='版权')menu.add_cascade(label='帮助', menu=forhelp)frm = Frame(self)frm_L = Frame(frm)frm_L.grid(row=0,column=10)frm_C = Frame(frm)frm_C.grid(row=0,column=20)frm_R = Frame(frm)frm_R.grid(row=0,column=30)canvas = Canvas(frm_L, width=400, height=400)canvas.pack(padx=5, pady=5)canvas.create_rectangle(30, 50, 350, 311)canvas = Canvas(frm_R, width=400, height=400)canvas.pack(padx=5, pady=5)canvas.create_rectangle(30, 50, 350, 311)  #(30,50)为正方形右上角坐标,(350,350)为正方形右下角坐标# 标签l_empty2 = Label(frm_C, height=2, ).grid(row=95, column=100)  # 空的,用来调位置l_times = Label(frm_C, text="迭 代 次 数:", height=2, ).grid(row=10, column=100)l_style = Label(frm_C, text="风 格 选 择:", height=2, ).grid(row=50, column=100)# 下拉列表self.comboxlist_times = ttk.Combobox(frm_C, textvariable=1, height=3, width=10)  # 初始化self.comboxlist_times["values"] = ("10", "20", "30", "40")self.comboxlist_times.grid(row=20, column=100)self.comboxlist_style = ttk.Combobox(frm_C, textvariable="梵高", height=3, width=10)  # 初始化self.comboxlist_style["values"] = ("梵高-星空", '梵高-播种者', "毕加索-斗牛", '毕加索-格尔尼卡', '米勒-拾穗')self.comboxlist_style.grid(row=60, column=100)# 按钮b_loader = Button(frm_C, text="加载图片", width=8,command=self.showImg).grid(row=100, column=100)  # 加载按钮b_trans = Button(frm_C, text="转换画风", width=8,command=self.catch).grid(row=5, column=100) # 转化按钮frm.pack()# 退出
def client_exit(self):exit()def showImg(self):# 1表示打开文件对话框dlg = win32ui.CreateFileDialog(1)dlg.DoModal()# 获取选择的文件名称self.name = dlg.GetPathName()# 以一个PIL图像对象打开  【调整待转图片格式】pil_image = Image.open(self.name)# 缩放图像让它保持比例,同时限制在一个矩形框范围内  【调用函数,返回整改后的图片】pil_image_resized = resize(325, 325, pil_image)# 把PIL图像对象转变为Tkinter的PhotoImage对象  【转换格式,方便在窗口展示】tk_image = ImageTk.PhotoImage(pil_image_resized)img = Label(self, image=tk_image,width=300,height=250)img.image = tk_imageimg.pack()img.place(x=45, y=60)def catch(self):base ='./' + self.comboxlist_style.get() +'.jpg'Change.Change(self.name, base, './Result', (int)(self.comboxlist_times.get()))result_name = './Result_at_iteration_%d.png' % ((int)(self.comboxlist_times.get()))pil_image = Image.open(result_name)# 缩放图像pil_image_resized = resize(325, 325, pil_image)# 把PIL图像对象转变为Tkinter的PhotoImage对象tk_image = ImageTk.PhotoImage(pil_image_resized)img = Label(self, image=tk_image,width=300,height=250)img.image = tk_imageimg.pack()img.place(x=550, y=60)

参数是:要适应的窗口宽、高、Image.open后的图片

def resize(w_box, h_box, pil_image):
# 获取图像的原始大小
w, h = pil_image.size
f1 = 1.0 * w_box / w
f2 = 1.0 * h_box / h
factor = min([f1, f2])
width = int(w * factor)
height = int(h * factor)
return pil_image.resize((width, height), Image.ANTIALIAS)

root=Tk()

设置界面大小

root.geometry(‘890x400’)

是否可以调节

root.resizable(width=False, height=False)
app = Window(root)
root.mainloop()

python实现图像渲染相关推荐

  1. python调整图像大小_使用Python调整图像大小

    作者|Nicholas Ballard 编译|VK 来源|Towards Data Science 可以说,每一个"使用计算机的人"都需要在某个时间点调整图像的大小.MacOS的预 ...

  2. python运行界面如何缩小_如何使用Python调整图像大小

    作者|Nicholas Ballard 编译|VK 来源|Towards Data Science 可以说,每一个"使用计算机的人"都需要在某个时间点调整图像的大小.MacOS的预 ...

  3. 使用Python调整图像大小

    作者|Nicholas Ballard 编译|VK 来源|Towards Data Science 可以说,每一个"使用计算机的人"都需要在某个时间点调整图像的大小.MacOS的预 ...

  4. LeetCode简单题之图像渲染

    题目 有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间. 给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 new ...

  5. Python 对图像进行base64编码及解码读取为numpy、opencv、matplot需要的格式

    Python 对图像进行base64编码及解码读取为numpy.opencv.matplot需要的格式 1. 效果图 2. 源码 参考 这篇博客将介绍Python如何对图像进行base64编解码及读取 ...

  6. 使用OpenCV和Python计算图像的“彩色度”

    使用OpenCV和Python计算图像"彩色度" 1. 效果图 2. 炫彩度量方法是什么? 3. 源代码 参考 你是否尝试过计算每个图像的炫彩值,并根据炫彩值对自己的图像数据集进行 ...

  7. 【python】图像映射:单应性变换与图像扭曲

    [python]图像映射:单应性变换与图像扭曲 单应性变换(Homography) 图像扭曲(仿射变换) 图中图 分段仿射扭曲 单应性变换(Homography) 单应性变换(Homography)即 ...

  8. Python计算机视觉——图像到图像的映射

    Python计算机视觉--图像到图像的映射 文章目录 Python计算机视觉--图像到图像的映射 写在前面 1 单应性变换 1.1 直接线性变换算法 1.2 仿射变换 2 图像扭曲 2.1 图像中的图 ...

  9. 使用 Python 的图像隐写术

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 今天,世界正在见证前所未有的数据爆炸,我们每天产生的数据量确实令人 ...

最新文章

  1. DAS工具: 利用去重、聚合和评分的策略从宏基因组中恢复基因组
  2. redis集群部署步骤
  3. easyUI menu动态添加
  4. 韦恩图——帮助你更好地表达多个数据集合之间的相交关系
  5. latex大写运算符号
  6. 探探自动配对PHP_CentOS7 - 安装Apache HTTP Server和PHP
  7. linux如何手动释放内存吗,Linux如何手动清理内存中cache信息
  8. C语言 makefile
  9. java实现ftp连接、登陆、上传、下载、删除文件、获取目录、文件列表
  10. 药品信息管理系统php,医药行业信息化管理系统
  11. 软件项目运维内容 软件系统运维工作内容
  12. python pytz_python pytz是什么
  13. HP惠普服务器驱动下载地址
  14. 行频、场频与分辨率、刷新率
  15. 第十二届蓝桥杯大赛软件赛省赛 Python 大学 A 组 部分试题与解析
  16. python库-collections模块Counter类
  17. 8脚51单片机DIY时间显示+闹钟技术分享(一)
  18. 每日一面 - java里的wait()和sleep()的区别有哪些?
  19. 前端:3分钟实现一个共享桌面,还能听见麦克风声音哦
  20. HTML(二)列表、表格、表单元素

热门文章

  1. A. One and Two
  2. 入手佳能24-70mm f/2.8L
  3. 视频号如何发表视频呢?
  4. 三国群雄传ol服务器 修改,三国群雄传四大兵营进阶改造攻略详解
  5. h5中performance.timing轻松获取网页各个数据 如dom加载时间 渲染时长 加载完触发时间...
  6. 解密暗池:那些不为人知的交易
  7. 为什么计算机里没有桌面显示不出来,电脑开机后桌面显示不出来如何修复_电脑开机后桌面没有东西的处理办法-系统城...
  8. 基本光照与阴影(一)
  9. 占豪--2010年的市场机会在哪里(兼谈股指期货与楼市)
  10. 深入浅出的图神经网络,神经调节的知识网络图