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

使用cv2.rectangle触发TypeError的问题排查求助

问题排查与解决

错误根源

报错TypeError: only size-1 arrays can be converted to Python scalars的核心原因:

  • res = model.predict(x_test)返回的是二维数组,形状为(样本数量, 类别数量),比如你的3分类任务中,若x_test包含N个样本,res就是(N,3)的数组。
  • 直接将整个res传入prob_viz后,enumerate(res)遍历的是每个样本的概率数组(每个prob是长度为3的数组),而非单个类别的概率值。此时int(prob*100)试图把数组转换为整数,必然触发类型错误。

修正方案

1. 传入单个样本的预测结果

你需要从res中取出单个样本的概率分布传入函数,比如取第一个样本的结果res[0]:

plt.figure(figsize=(18,18))
# 取单个样本的预测结果,而非整个res数组
plt.imshow(prob_viz(res[0], actions, image, colors)) 

2. 修复颜色通道不匹配问题(可选但重要)

OpenCV处理的图像是BGR通道顺序,而matplotlib的imshow默认使用RGB顺序,直接显示会导致颜色异常。需要在prob_viz函数中转换通道:

colors = [(245,117,16), (117,245,16), (16,117,245)]
def prob_viz(res, actions, input_frame, colors):
    # 转换BGR到RGB,适配matplotlib显示
    output_frame = cv2.cvtColor(input_frame.copy(), cv2.COLOR_BGR2RGB)
    for num, prob in enumerate(res):
        # 此时prob是单个浮点数,可正常转换为整数
        cv2.rectangle(output_frame, (0,60+num*40), (int(prob*100), 90+num*40), colors[num], -1)
        cv2.putText(output_frame, actions[num], (0, 85+num*40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)
        
    return output_frame

3. 批量可视化多个样本(可选)

如果需要查看多个样本的预测结果,可循环遍历res中的每个样本:

# 遍历前3个样本的预测结果
for idx in range(3):
    plt.figure(figsize=(18,18))
    plt.imshow(prob_viz(res[idx], actions, image, colors))
    plt.title(f"Sample {idx+1} Prediction")
    plt.show()

关键验证点

调用函数前打印以下内容,确认数据形状符合预期:

print("res的形状:", res.shape)       # 应为(N, 3),N是样本数
print("单个样本的形状:", res[0].shape) # 应为(3,)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:25:15