【已解决】YOLO11模型转wts时报错:PytorchStreamReader failed reading zip archive

问题:在把训练好的新YOLO11s模型转wts文件时报错,具体信息如下图(PytorchStreamReader failed reading zip archive: failed finding central directory)

解决:新老版本pytorch之间的兼容问题,改动一下生成wts文件即可。代码帖在下面。

python 复制代码
import sys  # noqa: F401
import argparse
import os
import struct
import torch


def parse_args():
    parser = argparse.ArgumentParser(description='Convert .pt file to .wts')
    parser.add_argument('-w', '--weights', required=True,
                        help='Input weights (.pt) file path (required)')
    parser.add_argument(
        '-o', '--output', help='Output (.wts) file path (optional)')
    parser.add_argument(
        '-t', '--type', type=str, default='detect', choices=['detect', 'cls', 'seg', 'pose', 'obb'],
        help='determines the model is detection/classification')
    args = parser.parse_args()
    if not os.path.isfile(args.weights):
        raise SystemExit('Invalid input file')
    if not args.output:
        args.output = os.path.splitext(args.weights)[0] + '.wts'
    elif os.path.isdir(args.output):
        args.output = os.path.join(
            args.output,
            os.path.splitext(os.path.basename(args.weights))[0] + '.wts')
    return args.weights, args.output, args.type


pt_file, wts_file, m_type = parse_args()

print(f'Generating .wts for {m_type} model')

# Load model
print(f'Loading {pt_file}')

# Initialize
device = 'cpu'

# Load model
model = torch.load(pt_file, map_location=device, weights_only=False)  # Load FP32 weights
model = model['ema' if model.get('ema') else 'model'].float()

if m_type in ['detect', 'seg', 'pose', 'obb']:
    anchor_grid = model.model[-1].anchors * model.model[-1].stride[..., None, None]

    delattr(model.model[-1], 'anchors')

model.to(device).eval()

with open(wts_file, 'w') as f:
    f.write('{}\n'.format(len(model.state_dict().keys())))
    for k, v in model.state_dict().items():
        vr = v.reshape(-1).cpu().numpy()
        f.write('{} {} '.format(k, len(vr)))
        for vv in vr:
            f.write(' ')
            f.write(struct.pack('>f', float(vv)).hex())
        f.write('\n')
相关推荐
春日见19 小时前
眼在手上外参标定保姆级教学---离线手眼标定(vscode + opencv)
linux·运维·开发语言·人工智能·数码相机·计算机视觉·matlab
SmartBrain19 小时前
对比:Qwen-VL与传统的CNN在图像处理应用
图像处理·人工智能·cnn
阿_旭19 小时前
Python中3类目标检测方法详解:从原理到实践
python·目标检测
全栈独立开发者21 小时前
架构师日记:当点餐系统遇上 AI —— 基于 Spring AI + Pgvector + DeepSeek 的架构设计思路
人工智能
谷歌开发者21 小时前
Web 开发指向标|开发者工具 AI 辅助功能的 5 大实践应用
前端·人工智能
kkai人工智能1 天前
AI写作:从“废话”到“爆款”
开发语言·人工智能·ai·ai写作
吴佳浩1 天前
Python入门指南(五) - 为什么选择 FastAPI?
后端·python·fastapi
寰天柚子1 天前
Java并发编程中的线程安全问题与解决方案全解析
java·开发语言·python
づ安眠丶乐灬1 天前
计算机视觉中的多视图几何 - 1
人工智能·vscode·计算机视觉