Open
Conversation
添加异常处理:
model = keras.models.load_model('model.h5'):如果模型文件缺失或损坏,程序将抛出错误,因此我们在加载模型时添加了异常处理,以便在加载失败时给予提示。
在 predict_digit 函数中添加了异常处理,以防止处理图像时发生错误,程序能够继续执行其他图像的预测,而不会因一个错误导致整体中断。
提取预测函数:
将图像处理和预测功能封装到 predict_digit 函数中,使代码结构更清晰、便于维护和复用。
检查 img 文件夹是否存在:
程序在开始时检查 img 文件夹的存在性,并在不存在时终止程序,避免无效路径导致的错误。
图像数组数据类型:
img = np.array(img, dtype=np.float32):在转换为 NumPy 数组时指定数据类型为 float32,这是深度学习模型中常用的浮点数据类型,能提高计算效率并减少内存消耗。
路径处理:
os.path.join('img', file_name):使用 os.path.join 构建路径,提高了代码的跨平台兼容性,避免在不同系统上路径分隔符差异导致的错误。
移除不必要的输入等待:
移除了 input("Press Enter to end..."),避免程序运行结束后还需额外操作,尤其适合在脚本执行自动化场景中使用。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
添加异常处理:
model = keras.models.load_model('model.h5'):如果模型文件缺失或损坏,程序将抛出错误,因此我们在加载模型时添加了异常处理,以便在加载失败时给予提示。 在 predict_digit 函数中添加了异常处理,以防止处理图像时发生错误,程序能够继续执行其他图像的预测,而不会因一个错误导致整体中断。 提取预测函数:
将图像处理和预测功能封装到 predict_digit 函数中,使代码结构更清晰、便于维护和复用。
检查 img 文件夹是否存在:
程序在开始时检查 img 文件夹的存在性,并在不存在时终止程序,避免无效路径导致的错误。
图像数组数据类型:
img = np.array(img, dtype=np.float32):在转换为 NumPy 数组时指定数据类型为 float32,这是深度学习模型中常用的浮点数据类型,能提高计算效率并减少内存消耗。 路径处理:
os.path.join('img', file_name):使用 os.path.join 构建路径,提高了代码的跨平台兼容性,避免在不同系统上路径分隔符差异导致的错误。 移除不必要的输入等待:
移除了 input("Press Enter to end..."),避免程序运行结束后还需额外操作,尤其适合在脚本执行自动化场景中使用。