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

Keras Captcha OCR如何传入单张jpeg到已训练模型获取字符串预测结果

Keras Captcha OCR 单张JPEG推理解决方案

1. 构建推理专用子模型

训练阶段的模型为了计算CTC损失同时传入了图像和标签,推理阶段只需提取图像输入到分类输出的链路即可:

from tensorflow import keras
import tensorflow as tf
import numpy as np

# 导入自定义CTCLayer(和训练时的CTCLayer定义完全一致)
from your_custom_module import CTCLayer

# 加载训练好的完整模型
trained_model = keras.models.load_model(
    'trained_models/my_trained_model.h5',
    custom_objects={'CTCLayer': CTCLayer}
)

# 构建仅用于推理的子模型
prediction_model = keras.models.Model(
    inputs=trained_model.get_layer(name="image").input,
    outputs=trained_model.get_layer(name="dense2").output
)

2. 单张图像预处理

预处理逻辑必须和训练阶段完全对齐,避免形状不匹配问题:

def preprocess_single_image(img_path):
    # 读取图像文件
    img = tf.io.read_file(img_path)
    # 解码为单通道灰度图
    img = tf.io.decode_jpeg(img, channels=1)
    # 像素值归一化到0-1区间
    img = tf.image.convert_image_dtype(img, tf.float32)
    # 尺寸对齐训练参数:高度50,宽度200
    img = tf.image.resize(img, [50, 200])
    # 转置维度适配RNN时序输入要求:[宽度, 高度, 通道数]
    img = tf.transpose(img, perm=[1, 0, 2])
    # 增加batch维度,适配模型输入要求
    return tf.expand_dims(img, axis=0)

3. CTC解码得到字符串结果

需要使用和训练时完全一致的字符集完成数值到字符的映射:

# 替换为你训练时使用的字符集合,顺序必须和训练时完全一致
characters = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
# 替换为你训练时设置的验证码最大长度
max_label_length = 5

def decode_ctc_output(pred):
    # 计算CTC解码所需的输入长度
    input_len = np.ones(pred.shape[0]) * pred.shape[1]
    # 贪心算法解码
    decode_result = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][:, :max_label_length]
    # 数值映射为字符
    output_text = []
    for res in decode_result:
        valid_chars = [characters[num] for num in res if num != -1]
        output_text.append(tf.strings.reduce_join(valid_chars).numpy().decode("utf-8"))
    return output_text

# 完整调用流程
img_path = '/test/my_image.jpeg'
processed_img = preprocess_single_image(img_path)
pred_result = prediction_model.predict(processed_img, verbose=0)
final_text = decode_ctc_output(pred_result)[0]
print(final_text)

注意事项:

  • 若调用get_layer时报错,可执行trained_model.summary()查看所有层的实际名称后替换
  • image.load_img的target_size参数顺序为(高度, 宽度),不要和模型输入的宽高顺序搞反
  • 字符集顺序错误会直接导致解码结果乱码,必须和训练阶段保持完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:09:03