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

图像分类器预测遇InvalidArgumentError:输入文件名需为标量

解决InvalidArgumentError:输入文件名需为标量

问题原因

你调用fd函数时传入了列表[im],但tf.io.read_file要求输入单个文件名(标量字符串),而非列表,因此触发报错。此外原代码还有个隐藏问题:tf.io.read_file返回的是文件内容字符串,不能直接用tf.image.resize,必须先解码为图像张量。

快速解决:修改调用代码

直接传入单个文件名字符串,同时调整返回值索引:

im = "/content/1000_IM-0003-1001.dcm.png"
matches = fd(t_embeddings, 
             im,  # 去掉外层列表,直接传字符串
             normalize=True)[0]  # 返回结果是二维列表,取第一个元素
# 用遍历避免索引越界,防止k值小于9时出错
for result in matches:
  print(result)

进阶方案:修改函数支持批量图像

如果需要一次性处理多张图像,修改函数以兼容列表输入,同时修复图像解码问题:

def fd(t_embeddings, imagesss, k=1, normalize=True):
  # 处理批量或单个图像输入
  if isinstance(imagesss, list):
    imgr_list = []
    for img_path in imagesss:
      # 读取文件后解码为图像张量
      img_raw = tf.io.read_file(img_path)
      img = tf.image.decode_png(img_raw, channels=3)  # 根据图像格式选decode_png/decode_jpeg
      img_resized = tf.image.resize(img, (299, 299))
      imgr_list.append(img_resized)
    # 堆叠为批量张量
    imgr = tf.stack(imgr_list)
  else:
    # 单个图像处理逻辑
    img_raw = tf.io.read_file(imagesss)
    img = tf.image.decode_png(img_raw, channels=3)
    imgr = tf.expand_dims(tf.image.resize(img, (299, 299)), axis=0)
  
  i_embedding = vision_encoder(imgr)
  if normalize:
    image_embeddings = tf.math.l2_normalize(t_embeddings, axis=1)
    query_embedding = tf.math.l2_normalize(i_embedding, axis=1)
  dot_similarity = tf.matmul(query_embedding, image_embeddings, transpose_b=True)
  results = tf.math.top_k(dot_similarity, k).indices.numpy()
  return [[df['findings'][idx] for idx in indices] for indices in results] 

调用时可正常传入列表:

im = "/content/1000_IM-0003-1001.dcm.png"
matches = fd(t_embeddings, 
             [im], 
             normalize=True)[0]
for result in matches:
  print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:50:25