2017-07-06 113 views
0

最近我想我在机用Python Tensorflow学习手,因为我与这两个产品的第一个项目,为我下学期做准备,但我有一个关于运行时遇到的问题,也许我大致的了解。如何快速高效地打开和操作图片?

我想创建一个程序:

  1. 加载一幅图片(从路径)
  2. 用途体面再次
  3. 输出的图片把所有的像素更绿损失函数和梯度。

好消息是,我还是设法做到这一点:

import tensorflow as tf 
import numpy as np 
from PIL import Image 
input = "pic.png" 
output = "output.png" 

file = Image.open(path) 
picture = np.array(file, np.float16) 
tenarray = tf.Variable(picture) #takes 20+ sec to run 

greenPic = np.empty([len(picture[:, 1]), len(picture[1]), 3], dtype=np.float16) 
greenPic[:, :, 1] = 250 
comparisonPic = tf.Variable(greenPic) #takes 20+ sec to run 


picComparison = tf.reduce_mean(-tf.reduce_sum(comparisonPic * tf.log(tenarray))) 

rate = 0.05 
trainingStep = tf.train.GradientDescentOptimizer(rate).minimize(picComparison) 

with tf.Session() as sesh: 
    sesh.run(tf.global_variables_initializer()) #Sets our variables, gets ready to run. 
    for i in range(100): 
     sesh.run(trainingStep) 

resultArray = sesh.run(tenarray) 

#Save picture 

的问题是,代码需要45个secounds运行,这基本上是闲置的2 * 22秒〜1秒实际计算。

我已经作出更快的版本,但他们都无法操纵的图片,或拒绝编译。 有没有人有一个好主意如何做到这一点,这是更高效?

+0

你从哪里得到这些数字(怠速44秒,计算1秒)?你的程序在哪里发生空转? –

+0

我通过添加计时(time.time())并测量出来了。 称取20秒+是分配tf.Variable人名的线的线tenarray和comparisonPic。 – Nodine

+0

@Nodine - 你为什么认为这是闲置的?训练模型是所有计算最密集的部分。 – zwer

回答

0

我设法解决这个我自己,所以如果有人碰巧碰上由于某种原因,同样的问题,我会在这里发表评论。

的问题是使用tf.float16的,而不是tf.float32对图像张量,改变这令上面运行的代码快给我50倍。

所以:

picture = tf.Variable(np.asarray(file, np.float32), tf.float32) 
... 
comparisonPic = tf.Variable(np.asarray(greenPic), tf.float32)