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

运行TensorFlow目标检测代码时出现long()参数必须为字符串或数字错误

解决TensorFlow目标检测中long() argument must be a string or a number错误

我之前在跑TensorFlow目标检测代码时也碰到过一模一样的问题,大概率是版本兼容或者标签文件加载的问题,给你几个亲测有效的解决思路:

1. 优先排查TensorFlow版本匹配问题

这个错误最常见的原因是目标检测API和TensorFlow版本不兼容:

  • 如果你的代码是基于TF1.x写的(比如用到了tf.Session()这类旧API),建议直接降级到TensorFlow 1.15.x(最后一个稳定的TF1版本):
    pip install tensorflow==1.15.5
    
  • 要是想升级到TF2.x环境,就得用适配TF2的目标检测API版本,同时修改代码里的兼容部分,比如把旧的会话初始化换成兼容写法:
    # 替换原有的session初始化代码
    tf.compat.v1.disable_eager_execution()
    sess = tf.compat.v1.Session()
    

2. 检查标签映射文件的格式与加载逻辑

这个错误经常出现在加载label_map.pbtxt的时候,一定要确认:

  • 标签文件格式完全正确,每个item的id必须是数字,name是字符串,比如:
    item {
      id: 1
      name: 'person'
    }
    item {
      id: 2
      name: 'car'
    }
    
  • 加载标签时用对应版本的API方法,避免类型转换错误:
    # TF1.x 标准写法
    label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
    categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
    category_index = label_map_util.create_category_index(categories)
    
    # TF2.x 简化写法
    category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
    

3. 确认模型文件完整性

如果你的模型是用export_inference_graph.py导出的,一定要确保导出过程没有报错,frozen_inference_graph.pb这类核心文件完整无损坏。可以重新导出一次模型,导出时注意指定和当前TF版本匹配的参数。

4. 排查输入图像的预处理问题

偶尔也会因为输入图像的数据类型不对触发这个错误,确保图像读取后转换成了正确的数值类型:

image = Image.open(image_path)
# 强制转换成uint8类型,避免类型不兼容
image_np = np.array(image).astype(np.uint8)

内容的提问来源于stack exchange,提问作者M.N Engineering

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:10:28