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

Python中如何通过Google Drive链接读取YOLO预训练模型?

问题原因
  • 你使用的Google Drive链接是文件预览页面地址,并非权重文件的直接下载地址,requests.get返回的是HTML网页内容,不是YOLO .weights文件的二进制数据。
  • cv2.dnn.readNetFromDarknet的第二个入参仅支持本地权重文件的路径字符串,不识别requests返回的Response对象,即使你传入rsrc.content原始字节也无法被该接口直接读取。
  • 若模型文件大于100MB,Google Drive会弹出病毒扫描确认跳转,普通GET请求无法直接获取到完整的文件内容。
可行实现方案

不需要持久化保存文件到本地磁盘,可通过生成临时文件的方式实现内存级读取:

  1. 先将Google Drive分享链接转换为直接下载链接,转换规则为将原链接中FILE_ID提取出来,拼接为https://drive.google.com/uc?export=download&id=FILE_ID格式,你的文件对应下载链接为https://drive.google.com/uc?export=download&id=1-Mj6c9ctPoYx3akhvqPJojSl3T-ihey_
  2. 使用tempfile模块生成临时文件存储下载的权重内容,读取完成后临时文件会被自动回收,不会在本地留存。

修正后可运行代码

import cv2
import requests
import tempfile
import os

# 替换为转换后的Google Drive直接下载链接
weight_url = 'https://drive.google.com/uc?export=download&id=1-Mj6c9ctPoYx3akhvqPJojSl3T-ihey_'
# 大文件场景可添加params={'confirm': 't'}参数跳过Google Drive扫描确认
response = requests.get(weight_url)

# 生成临时文件存储权重
with tempfile.NamedTemporaryFile(suffix='.weights', delete=False) as f:
    f.write(response.content)
    temp_weight_path = f.name

try:
    # 读取配置和临时权重文件加载模型
    net = cv2.dnn.readNetFromDarknet('files//yolov3-spp.cfg', temp_weight_path)
    # 后续执行你的预测逻辑
finally:
    # 手动删除临时文件,确保本地不留存权重
    os.unlink(temp_weight_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:06:03