python - Tensorflow 预测错误,invalidArgumentError:断言失败:[无法将字节解码为 JPEG、PNG、GIF 或 BMP]
问题描述
我使用 Google 对象检测 Api 训练了一个 Tensorflow Ssd 对象检测模型,并使用提供的“export_inference_graph.py”脚本将训练后的模型导出为“Saved_model.pb”文件,其中“encoded_image_string_tensor”作为输入类型,但是当我尝试对模型进行预测,我收到以下错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [Unable to decode bytes as JPEG, PNG, GIF, or BMP]
© 将模型加载到图表中,如下所示:
with tf.Session() as sess:
tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], saved_model_file)
graph = tf.get_default_graph()
并做出如下预测:
# Convert the image into base64 encoded string
img = Image.open(IMAGE_PATH)
resized_img = img.resize((300, 300), Image.ANTIALIAS)
binary_io = io.BytesIO()
resized_img.save(binary_io, "JPEG")
bytes_string_image = base64.b64encode(binary_io.getvalue()).decode("utf-8")
# Define the input and output placeholder tensors
input_tensor = graph.get_tensor_by_name('encoded_image_string_tensor:0')
tensor_dict = {}
for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes']:
tensor_name = key + ':0'
tensor_dict[key] = graph.get_tensor_by_name(tensor_name)
# Finally, do the prediciton
output_dict = sess.run(tensor_dict, feed_dict={
input_tensor: bytes_string_image})
解决方案
似乎在创建 TFRecords 时,只支持 jpeg 图像,并且在文档中没有指出这一点!同样,当您尝试使用其他类型时,它不会发出任何警告或不会通过任何异常,因此像我这样的人会浪费大量时间来调试可以很容易地发现并首先修复的东西。无论如何,将所有图像转换为 jpg 解决了这个奇怪的地狱问题。
你也可以检查这个问题: https ://github.com/tensorflow/tensorflow/issues/13044
该程序将挑选出实际上不是 jpeg 的文件。删除它们然后你就可以走了。""" 导入 imghdr
导入 cv2
导入os
导入 glob
对于 ['train', 'test'] 中的文件夹:
image_path = os.path.join(os.getcwd(), ('images/' + 文件夹))
print(image_path)
用于 glob.glob 中的文件(image_path + ' /*.jpg'):
image = cv2.imread(file)
file_type = imghdr.what(file)
if file_type != 'jpeg':
print(file + " - invalid - " + str(file_type))
cv2.imwrite(文件,图像)
"""
推荐阅读
- python - 如何计算列的唯一值并将每个值附加到字典中?
- python - 获取熊猫数据框中列的先前非 NaN 值以进行计算
- typescript - 使用 ts-loader 时解决类型依赖的问题,但不使用 tsc
- reactjs - 在我的 react-navigation/material-bottom-tabs 上添加通知计数器徽章
- angular - 防止 Angular Material 自动完成溢出页面容器
- android - 如何在 React Native 中制作 Android 手电筒
- python - 将小数字转换为从 0 到 10 的范围
- json - Chrome 83 开发工具“网络预览”选项卡应显示格式化的 JSON 响应时为空白
- python - Python 请求,下载 Overpass Turbo XML
- javascript - Gatsby Server Rendering APIs 和 next js 中的 ssr 是一样的吗?