You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TensorFlow推理阶段传入自定义图像?附推理模型代码

在TensorFlow推理阶段传入自定义图像的实现方法

嘿,我帮你梳理下怎么把自定义图像传入这个推理模型里,核心就是把图像转换成模型预期的输入格式,再喂进inference函数就行,一步步来:

第一步:对齐训练时的图像预处理逻辑

模型的输入images是符合训练规格的张量,自定义图像必须先做和训练完全一致的预处理,不然推理结果会跑偏:

  • 读取并转换图像格式:用PIL或OpenCV读取图像,确保通道顺序和训练时一致(比如训练用RGB就转成RGB),示例代码:
    from PIL import Image
    img = Image.open("你的图像路径.jpg").convert('RGB')
    
  • 调整图像尺寸:得匹配模型的输入尺寸,从你代码里的coarse1卷积(11x11核、步长4的VALID padding)推测,训练时输入可能是227x227(类似AlexNet输入),所以把图像resize到对应尺寸:
    target_size = (227, 227)  # 换成你训练时实际用的输入尺寸
    img = img.resize(target_size)
    
  • 归一化像素值:和训练时的预处理逻辑对齐,比如训练时把像素缩到0-1范围:
    import numpy as np
    img_array = np.array(img) / 255.0  # 从0-255映射到0-1
    
  • 增加Batch维度:模型的images输入是批量张量(形状为[batch_size, height, width, channels]),单张图像要扩展成[1, h, w, 3]:
    import tensorflow as tf
    img_tensor = tf.convert_to_tensor(img_array, dtype=tf.float32)
    img_tensor = tf.expand_dims(img_tensor, axis=0)
    

第二步:调用推理函数执行预测

预处理好的张量可以直接传给inference函数了,注意推理时要设置trainable=False(让BN、Dropout等层切换到推理状态),reuse参数根据场景设置:第一次构建图设False,加载预训练权重后复用变量设True。

完整的推理示例代码:

import tensorflow as tf
from PIL import Image
import numpy as np

# 先保留你的conv2d和inference函数实现
def conv2d(name, inputs, kernel_shape, bias_shape, strides, padding, reuse, trainable):
    with tf.variable_scope(name, reuse=reuse):
        kernel = tf.get_variable('kernel', kernel_shape, trainable=trainable)
        bias = tf.get_variable('bias', bias_shape, trainable=trainable)
        conv = tf.nn.conv2d(inputs, kernel, strides=strides, padding=padding)
        return tf.nn.bias_add(conv, bias)

def inference(images, reuse=False, trainable=True):
    coarse1_conv = conv2d('coarse1', images, [11, 11, 3, 96], [96], [1, 4, 4, 1], padding='VALID', reuse=reuse, trainable=trainable)
    coarse1 = tf.nn.max_pool(coarse1_conv, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID', name='pool1')
    # 补全你剩下的模型结构代码
    # ...
    return coarse1  # 替换成你的模型实际输出层

# 封装预处理函数
def preprocess_image(image_path, target_size=(227, 227)):
    img = Image.open(image_path).convert('RGB')
    img = img.resize(target_size)
    img_array = np.array(img) / 255.0
    img_tensor = tf.convert_to_tensor(img_array, dtype=tf.float32)
    return tf.expand_dims(img_tensor, axis=0)

# 执行推理流程
with tf.Graph().as_default():
    # 加载并预处理自定义图像
    input_img = preprocess_image("test_image.jpg")
    # 调用推理函数,开启推理模式
    model_output = inference(input_img, reuse=False, trainable=False)
    
    # 加载训练好的模型权重
    saver = tf.train.Saver()
    with tf.Session() as sess:
        # 替换成你的模型checkpoint文件路径
        saver.restore(sess, "./trained_model.ckpt")
        # 运行得到推理结果
        result = sess.run(model_output)
        print("推理输出结果:", result)

关键注意点

  • 严格对齐预处理:尺寸、归一化方式、通道顺序必须和训练时完全一致,这是推理结果准确的核心前提
  • 推理模式切换:trainable=False会让模型中的BatchNorm、Dropout等层切换到推理状态,避免干扰结果
  • 变量复用:如果在已有的计算图中重复调用inference,要设置reuse=True,否则会报变量重复定义的错误

内容的提问来源于stack exchange,提问作者Roarer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:33:10