for循环拼接数组时OpenVINO推理输出numpy形状不符合预期
问题原因
- 你将模型输入reshape为
[1, 128, 128, 1]的带batch位的固定形状,对应推理输出自然也保留了第0位长度为1的batch维度,单轮输出形状为(1, 128, 128, 1)。你直接将带batch维度的输出存入列表,最终转numpy数组时,83个4维张量会沿新的第0维拼接,自然得到5维的(83, 1, 128, 128, 1)结果。 - 你当前代码存在明显性能问题:将OpenVINO核心初始化、模型读取、模型reshape、模型编译的逻辑全写在for循环内部,83次循环会重复执行83次模型加载编译操作,推理速度会非常慢。
- 你注释掉了
infer_request.set_input_tensor(input_tensor)行,这行负责将你构造的输入张量绑定到推理请求上,不取消注释的话,推理不会使用你传入的裁剪后图像数据,结果会完全错误。
解决方法
- 将模型加载、编译、推理请求初始化的逻辑全部移到for循环外部,全流程只执行一次,避免重复加载编译模型浪费时间。
- 每轮拿到推理输出后,先通过numpy的
squeeze()方法移除长度为1的batch维度,再存入结果列表,单轮输出形状就会变为目标的(128, 128, 1)。 - 结果列表直接初始化为空列表,每轮处理完输出后用
append()方法追加结果即可,不需要提前按索引预分配位置,最终转numpy数组时不需要指定dtype=object,直接转换即可得到目标形状。 - 取消
infer_request.set_input_tensor(input_tensor)行的注释,确保输入图像正确绑定到推理请求。
修正后的核心代码如下:
import numpy as np import cv2 import openvino.runtime as ov # 模型初始化逻辑移到循环外,仅执行一次 core = ov.Core() model = core.read_model(model="model/saved_model_A4C_LV/saved_model.xml") model.reshape([1, 128, 128, 1]) compiled_model = core.compile_model(model, "CPU") infer_request = compiled_model.create_infer_request() output_buffer_LV_arr = [] for i in range(ds_arr.shape[0]): # 省略你原有的DICOM切片处理、JPG保存、图像裁剪逻辑 LV_corp = cv2.imread("0.jpg", cv2.IMREAD_GRAYSCALE) print("corp:", LV_corp.shape) input_tensor = ov.Tensor(array=LV_corp, shared_memory=True) infer_request.set_input_tensor(input_tensor) # 取消该行注释 infer_request.start_async() infer_request.wait() output = infer_request.get_output_tensor() # 移除长度为1的batch维度 output_buffer_LV = output.data.squeeze() print("single output shape:", output_buffer_LV.shape) output_buffer_LV_arr.append(output_buffer_LV) output_buffer_LV_arr = np.array(output_buffer_LV_arr) print("final output_LV shape:", output_buffer_LV_arr.shape)
运行后单轮输出形状为(128, 128, 1),最终输出数组形状为目标的(83, 128, 128, 1),可直接输入到后续支持动态batch的模型中。
内容的提问来源于stack exchange,提问作者TseHsien
相关产品推荐
相关产品推荐

