TensorFlow:在图形定义中存储扭曲

2024-03-29 07:14:13 发布

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

下面是我用来部署训练过的TensorFlow模型的一些代码。它基本上只是从一个.pb文件中加载模型,获取模型的第一层和最后一层,并计算图像。这工作得很好,但我想部署许多不同的图像尺寸和扭曲,如模糊,白化和旋转模型。你知道吗

我的问题是:图像失真序列可以存储在.pb文件中吗?如果是,怎么做?你知道吗

目标是最小化部署脚本中的代码量。你知道吗

import base64
import math
import os
import tensorflow as tf

def get_graph():
    if os.path.isfile('./graph.pb'):
        graph_def = tf.GraphDef()
        with open('./graph.pb', 'rb') as graph_file:
            graph_def.ParseFromString(graph_file.read())
    else:
        raise Exception('Graph file \'./graph.pb\' does not exist')
    return graph_def

def init(event):
    graph_def = get_graph()

    with tf.Session() as session:
        session.graph.as_default()
        tf.import_graph_def(graph_def, name = '')

        stringified = base64.b64decode(event['image'].split(',')[1])
        decoded = tf.image.decode_jpeg(stringified, channels = 3)
        decoded.set_shape([event['height'], event['width'], 3])
        image = tf.cast(decoded, tf.float32)

        evaluation = image.eval(sessions = sess)

        input_tensor = sess.graph.get_tensor_by_name('input_placeholder:0')
        output_tensor = sess.graph.get_tensor_by_name('softmax_linear/softmax_linear:0')

        feed_dict = { input_tensor: evaluation }
        result = sess.run([output_tensor], feed_dict = feed_dict)
        return result

Tags: 模型图像imageimporteventgettf部署
1条回答
网友
1楼 · 发布于 2024-03-29 07:14:13

答案取决于原始graph.pb是如何生成的。你知道吗

如果您已经修改了产生原始graph.pb的脚本,您可以简单地向该脚本添加重塑、扭曲等操作,并重新生成graph.pb。请注意,您必须删除旧的input_placeholder操作,并将预处理操作的输出连接到input_placeholder正在传送的操作的输入。您的新占位符将只接受stringified作为输入。你知道吗

如果无法修改生成原始graph.pb的脚本,则可以通过将预处理子图保存到自己的.pb中来减少部署脚本中的代码量。比如:

raw_input = tf.placeholder(tf.string)
decoded = tf.image.decode_jpeg(raw_input, channels = 3)
decoded.set_shape([event['height'], event['width'], 3])
image = tf.cast(decoded, tf.float32)
with open('preprocess.pb', 'w') as f:
  f.write(tf.get_default_graph().as_graph_def())

然后可以将原始输入馈送到预处理子图,并将其输出(仍然通过eval调用获得)馈送到原始图。你知道吗

相关问题 更多 >