Python报错"No module named 'ultralytics'":PyInstaller打包YOLOv5程序异常
解决PyInstaller打包YOLOv5代码时"no module named 'ultralytics'"的问题
问题原因
PyInstaller无法自动识别通过torch.hub.load动态加载的ultralytics依赖,导致打包后的exe运行时找不到该模块。
解决步骤
先安装ultralytics模块
执行以下命令确保本地环境包含该依赖:pip install ultralytics修改代码,替换动态加载方式
将torch.hub.load改为直接导入ultralytics的YOLO类,让PyInstaller能检测到依赖:import cv2 import torch from PIL import Image import os from ultralytics import YOLO # 获取当前程序目录,确保模型路径正确 current_dir = os.path.dirname(os.path.abspath(__file__)) model = YOLO(os.path.join(current_dir, 'model.pt')) # opencv cam cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break pil_image = Image.fromarray(frame) results = model(pil_image) output_frame = results.render()[0] cv2.imshow('Object Detection', output_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()打包时显式指定隐藏依赖(若保留原代码)
如果不想修改代码,打包时用--hidden-import参数告诉PyInstaller包含ultralytics模块:pyinstaller --hidden-import=ultralytics --onefile your_script_name.py验证模型路径
打包后确保model.pt和exe文件在同一目录下,或用代码中的绝对路径方式指定模型位置,避免运行时找不到模型。
内容的提问来源于stack exchange,提问作者Kevin Yang
相关产品推荐
相关产品推荐

