如何快速有效地打开和操作图片?

2024-10-08 18:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,我尝试了用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秒,基本上是2*22秒的空闲时间和~1秒的实际计算时间。你知道吗

我已经做了更快的版本,但他们都无法操纵图片,或拒绝编译。 有没有人知道怎样做才能更有效?你知道吗


Tags: torunimageimportoutputpngtfas
1条回答
网友
1楼 · 发布于 2024-10-08 18:24:17

我自己解决了这个问题,所以如果有人因为某种原因遇到同样的问题,我会在这里发表评论。你知道吗

问题是使用tf.16浮动而不是tf.32浮动对于图像张量,更改此选项使上面的代码运行速度提高了50倍。你知道吗

所以:

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

相关问题 更多 >

    热门问题