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

如何在OpenVino中从二进制数据创建Blob::CPtr对象

OpenVINO ReadNetwork 内存加载权重Blob构造方案

以下是针对Inference Engine旧版API(适用2021及更早OpenVINO版本)的实现步骤:

  • 第一步:读取weights.bin的全部二进制数据到内存缓冲区,同时读取model.xml的全文内容到std::string变量
  • 第二步:使用TBlob<uint8_t>构造二进制权重Blob,再转为Blob::CPtr类型传入接口

完整代码示例

#include <fstream>
#include <vector>
#include <cstring>
#include <inference_engine.hpp>

using namespace InferenceEngine;

// 通用二进制文件读取工具
std::vector<uint8_t> read_binary_file(const std::string& file_path) {
    std::ifstream file(file_path, std::ios::binary | std::ios::ate);
    if (!file.is_open()) {
        throw std::runtime_error("Failed to open file: " + file_path);
    }
    size_t file_size = file.tellg();
    file.seekg(0, std::ios::beg);
    std::vector<uint8_t> data(file_size);
    file.read(reinterpret_cast<char*>(data.data()), file_size);
    return data;
}

int main() {
    // 读取模型和权重的原始数据
    std::vector<uint8_t> weights_raw = read_binary_file("weights.bin");
    std::ifstream xml_fs("model.xml");
    std::string model_xml_content((std::istreambuf_iterator<char>(xml_fs)), std::istreambuf_iterator<char>());

    // 构造权重Blob(拷贝模式,Blob自行管理内存,无需额外维护原始缓冲区生命周期)
    TensorDesc weight_desc(Precision::U8, {weights_raw.size()}, Layout::C);
    TBlob<uint8_t>::Ptr weight_blob = make_shared_blob<uint8_t>(weight_desc);
    weight_blob->allocate();
    memcpy(weight_blob->buffer(), weights_raw.data(), weights_raw.size());

    // 调用重载接口加载网络
    CNNNetwork network = ReadNetwork(model_xml_content, weight_blob);
    // 后续正常操作网络即可

    return 0;
}

可选零拷贝方案

如果希望减少一次内存拷贝,可以直接绑定外部缓冲区构造Blob,注意需要保证原始权重缓冲区在网络完全加载完成前不被释放:

TBlob<uint8_t>::Ptr weight_blob = make_shared_blob<uint8_t>(weight_desc, weights_raw.data());
// 不需要调用allocate方法

注意事项

  • 传入的xml内容必须是model.xml的完整文本,不能包含多余的格式字符
  • 权重数据的总长度必须和xml文件中描述的权重总字节数完全匹配,否则会触发加载错误
  • 2022.1及之后的OpenVINO版本已废弃该API,新版ov::Core::read_model内存加载接口使用ov::Tensor构造权重参数,逻辑和上述方案一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:45:05