yolo5---运行报错记录

报错1: ImportError: cannot import name 'TryExcept' from 'utils'

Traceback (most recent call last):
  File "/usr/local/lib/python3.11/dist-packages/IPython/core/interactiveshell.py", line 3550, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-388ad7e07587>", line 1, in <module>
    runfile('/media/pi/Lexar3/python_test/Visual_Test/models/yolo.py', wdir='/media/pi/Lexar3/python_test/Visual_Test/models')
  File "/home/pi/Downloads/pycharm-2024.1/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/pi/Downloads/pycharm-2024.1/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/media/pi/Lexar3/python_test/Visual_Test/models/yolo.py", line 24, in <module>
    from models.common import *  # noqa
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/pi/Downloads/pycharm-2024.1/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/pi/Lexar3/python_test/Visual_Test/models/common.py", line 49, in <module>
    from utils import TryExcept
ImportError: cannot import name 'TryExcept' from 'utils' (/media/pi/Lexar3/python_test/utils.py)

报错原因:因为打开目录不是yolov5的根目录,所以找不到yolov5文件夹下的utils模块

解决方案1:直接把文件夹名字加上

 
from utils import TryExcept, emojis
from utils.downloads import gsutil_getsize
from utils.metrics import box_iou, fitness
改成
from <.utils所在的文件夹名>.utils import TryExcept, emojis
from <.utils所在的文件夹名>.utils.downloads import gsutil_getsize
from <.utils所在的文件夹名>.utils.metrics import box_iou, fitness

解决方案2:直接打开源代码所在的文件夹

报错2:All git commands will error until this is rectified.

WARNING:tensorflow:From C:\Users\23665\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.

Traceback (most recent call last):
  File "C:\Users\23665\AppData\Local\Programs\Python\Python311\Lib\site-packages\git\__init__.py", line 296, in <module>
    refresh()
  File "C:\Users\23665\AppData\Local\Programs\Python\Python311\Lib\site-packages\git\__init__.py", line 287, in refresh
    if not Git.refresh(path=path):
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\23665\AppData\Local\Programs\Python\Python311\Lib\site-packages\git\cmd.py", line 631, in refresh
    raise ImportError(err)
ImportError: Bad git executable.
The git executable must be specified in one of the following ways:
    - be included in your $PATH
    - be set via $GIT_PYTHON_GIT_EXECUTABLE
    - explicitly set via git.refresh(<full-path-to-git-executable>)

All git commands will error until this is rectified.

This initial message can be silenced or aggravated in the future by setting the
$GIT_PYTHON_REFRESH environment variable. Use one of the following values:
    - quiet|q|silence|s|silent|none|n|0: for no message or exception
    - warn|w|warning|log|l|1: for a warning message (logging level CRITICAL, displayed by default)
    - error|e|exception|raise|r|2: for a raised exception

Example:
    export GIT_PYTHON_REFRESH=quiet


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "E:\python_test\Visual_Test\train.py", line 72, in <module>
    GIT_INFO = check_git_info()
               ^^^^^^^^^^^^^^^^
  File "C:\Users\23665\AppData\Local\Programs\Python\Python311\Lib\contextlib.py", line 81, in inner
    return func(*args, **kwds)
           ^^^^^^^^^^^^^^^^^^^
  File "E:\python_test\Visual_Test\utils\general.py", line 370, in check_git_info
    import git
  File "C:\Users\23665\AppData\Local\Programs\Python\Python311\Lib\site-packages\git\__init__.py", line 298, in <module>
    raise ImportError("Failed to initialize: {0}".format(_exc)) from _exc
ImportError: Failed to initialize: Bad git executable.
The git executable must be specified in one of the following ways:
    - be included in your $PATH
    - be set via $GIT_PYTHON_GIT_EXECUTABLE
    - explicitly set via git.refresh(<full-path-to-git-executable>)

All git commands will error until this is rectified.

This initial message can be silenced or aggravated in the future by setting the
$GIT_PYTHON_REFRESH environment variable. Use one of the following values:
    - quiet|q|silence|s|silent|none|n|0: for no message or exception
    - warn|w|warning|log|l|1: for a warning message (logging level CRITICAL, displayed by default)
    - error|e|exception|raise|r|2: for a raised exception

Example:
    export GIT_PYTHON_REFRESH=quiet

保存原因:git环境变量设置问题

解决·方案:在导入包的上方增加以下代码 

import os
os.environ["GIT_PYTHON_REFRESH"] = "quiet"

报错3:cv2.error: OpenCV(4.8.1) /io/opencv/modules/imgcodecs/src/loadsave.cpp:802: error: (-215:Assertion failed) !buf.empty() in function 'imdecode_'

(注:报错原因:我在使用绿联hdmi采集卡进行图像采集时所遇到的问题。)

M_predict_test: weights=yolov5s.pt, source=0, data=data/coco128.yaml, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_csv=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=1, hide_labels=False, hide_conf=False, half=False, dnn=False, vid_stride=180
YOLOv5 🚀 f573f3b Python-3.11.2 torch-2.1.2 CPU
Fusing layers... 
YOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients, 16.4 GFLOPs
WARNING ⚠️ Environment does not support cv2.imshow() or PIL Image.show()
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/dist-packages/IPython/core/interactiveshell.py", line 3550, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-148bbbd5c4c3>", line 1, in <module>
    runfile('/media/pi/Lexar3/python_test/Visual_Test/M_predict_test.py', wdir='/media/pi/Lexar3/python_test/Visual_Test')
  File "/home/pi/Downloads/pycharm-2024.1/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/pi/Downloads/pycharm-2024.1/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/media/pi/Lexar3/python_test/Visual_Test/M_predict_test.py", line 428, in <module>
    main(opt)
  File "/media/pi/Lexar3/python_test/Visual_Test/M_predict_test.py", line 423, in main
    run(**vars(opt))
  File "/home/pi/.local/lib/python3.11/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/media/pi/Lexar3/python_test/Visual_Test/M_predict_test.py", line 174, in run
    dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/pi/Lexar3/python_test/Visual_Test/utils/dataloaders.py", line 379, in __init__
    _, self.imgs[i] = cap.read()  # guarantee first frame
                      ^^^^^^^^^^
cv2.error: OpenCV(4.8.1) /io/opencv/modules/imgcodecs/src/loadsave.cpp:802: error: (-215:Assertion failed) !buf.empty() in function 'imdecode_'

解决方案:hdmi采集卡与摄像头断开再重新连接

报错四:File "/home/pi/python_test/Visual_Test/detect20250104.py", line 233, in run
    a = points_3d[int(y_0), int(x_0), 0] / 1000
        ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
IndexError: index 541 is out of bounds for axis 0 with size 480
terminate called without an active exception
Aborted

解决方案:在detetc.py文件中查看loadstream所在位置,如图下图所示。

找到后,更改 1、2处的数值,2处的代码是原本没有的,需要自己填上,同时images为1280是因为本文用的是双目摄像头,每个摄像头拍摄大小为640*480,两个摄像头所拍摄的大小则为1280*480。

### 解决方案 `CUDA error: device-side assert triggered` 是一种常见的 GPU 错误提示,通常表明在设备端发生了某种断言失败。这种错误可能由多种原因引起,尤其是在更改数据集标签后运行程序时更容易出现问题。 以下是可能导致该问题的具体原因及其对应的解决方案: #### 1. **标签格式不匹配** 如果新的数据集中标签的格式与模型预期不符,则可能会触发此错误。例如,在 YOLO 或 Faster R-CNN 中,目标检测框坐标超出范围或类别索引不符合要求都会引发此类问题[^5]。 - **验证标签文件** 打开并检查新数据集中的标签文件(如 `.txt` 文件),确保其内容符合模型的要求。对于 YOLOv3 来说,每行应遵循以下格式: ``` class_id center_x center_y width height ``` 其中 `center_x`, `center_y`, `width`, 和 `height` 都是以相对图像尺寸的比例表示的浮点数,取值应在 `[0, 1]` 范围内[^5]。 - **修复方法** 如果发现有异常值(如负数或大于 1 的数值),可以编写脚本对其进行修正。例如: ```python import os def fix_labels(label_dir): for label_file in os.listdir(label_dir): with open(os.path.join(label_dir, label_file), 'r') as f: lines = f.readlines() fixed_lines = [] for line in lines: parts = line.strip().split(' ') if len(parts) != 5 or not all(0 <= float(x) <= 1 for x in parts[1:]): continue # Skip invalid entries fixed_lines.append(line) with open(os.path.join(label_dir, label_file), 'w') as f: f.writelines(fixed_lines) fix_labels('/path/to/your/dataset/labels') ``` --- #### 2. **网络结构配置错误** 当更换数据集时,如果没有正确调整模型的相关参数(如分类数量、输入大小等),也可能导致 CUDA 错误。例如,YOLOv3 的 anchors 设置不当或者 Faster R-CNN 的 ROI Pooling 层输出维度设置不合理都可能是诱因之一[^4]。 - **确认超参一致性** 修改配置文件以适配新数据集。比如更新类别的总数目,并同步修改损失函数中的对应部分。 - **调试工具推荐** 建议通过单张随机 Tensor 输入测试整个前向传播过程是否正常工作,从而定位潜在隐患[^4]: ```python import torch from model import YourModelNameHere # 替换为实际使用的模型定义路径 devices = ['cuda'] if torch.cuda.is_available() else ['cpu'] net = YourModelNameHere(num_classes=new_dataset_num_classes).to(devices[0]) X = torch.rand(size=(batch_size, channels, height, width)).to(devices[0]) # 自定义合适的 batch size 及图片分辨率 try: output = net(X) print("Forward pass succeeded!") except Exception as e: print(f"Error during forward pass: {e}") ``` --- #### 3. **GPU 设备管理混乱** 有时多个进程争抢同一块显卡资源亦或是未指定确切的目标计算单元也会造成类似的崩溃现象[^4]。 - **强制绑定单一 GPU** 将环境变量设为仅允许访问特定编号的一台机器上的某个物理核心来规避冲突情况发生。 ```bash export CUDA_VISIBLE_DEVICES="0" python train.py --other-options... ``` - **启用逐层执行模式辅助排查** 开启 `CUDA_LAUNCH_BLOCKING=1` 参数有助于更精确地捕捉到哪一步骤引发了致命性的硬件级中断信号[^1][^4]。 ```bash export CUDA_LAUNCH_BLOCKING=1 python train.py --other-options... ``` --- #### 4. **内存泄漏或其他低层次编程缺陷** 尽管较为少见但仍需留意是否存在某些隐藏较深的技术债务影响到了整体稳定性表现。这包括但不限于越界读写数组元素位置、释放已经销毁的对象指针再次操作等等危险动作均有可能间接诱发上述症状出现[^3]. - **利用专业诊断软件分析堆栈轨迹信息进一步缩小可疑区域范围直至彻底根除根源所在为止** --- ### 总结 综上所述,针对 “CUDA error: device-side assert triggered after changing dataset labels”,可以从以下几个方面入手解决问题:一是仔细核验所有外部导入的数据质量尤其是标注记录本身的合法性;二是审慎校准内部算法逻辑框架使之能够良好适应当前场景需求变化趋势;三是妥善安排好软硬件协同作业关系减少不必要的干扰因素干扰;四是必要时候借助第三方插件完成深层次剖析挖掘根本成因以便采取针对性措施加以改进优化性能指标达成预期目的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值