打包yolov5的detect.py文件遇到问题。我的detect.py里面添加了读取txt文本和写入坐标的功能,运行正常,但是采用pyinstaller打包exe之后,运行会报错。说找不到txt文件。
torchvision\io\image.py:13: UserWarning: Failed to load image Python extension:
torch\_jit_internal.py:751: UserWarning: Unable to retrieve source for @torch.jit._overload function: <function _DenseLayer.forward at 0x0000022F3D3BC040>.
warnings.warn(f"Unable to retrieve source for @torch.jit._overload function: {func}.")
torch\_jit_internal.py:751: UserWarning: Unable to retrieve source for @torch.jit._overload function: <function _DenseLayer.forward at 0x0000022F3D3D33A0>.
warnings.warn(f"Unable to retrieve source for @torch.jit._overload function: {func}.")
detect: weights=C:/yilai/last.pt, source=C:/yilai/2022_12_7_random_test_image/High_quality_image, data=C:/yilai/FlowMeter_coco128.yaml, imgsz=[640, 640], conf_thres=0.7, iou_thres=0.45, max_det=1000, device=cpu, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=C:/yilai/detect, name=exp, exist_ok=False, line_thickness=2, hide_labels=False, hide_conf=False, half=False, dnn=False, vid_stride=1
requirements: C:\yolov5\Temp\_MEI60162\requirements.txt not found, check failed.
Traceback (most recent call last):
File "detect.py", line 267, in <module>
File "detect.py", line 262, in main
File "torch\autograd\grad_mode.py", line 27, in decorate_context
File "detect.py", line 96, in run
File "utils\torch_utils.py", line 109, in select_device
File "utils\general.py", line 267, in file_date
File "pathlib.py", line 1198, in stat
FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'C:\\yolov5\\Temp\\_MEI60162\\utils\\general.pyc'
[16552] Failed to execute script 'detect' due to unhandled exception!
我的的detect.py代码如下:
# 该段代码是输出识别的种类和坐标
object_name = names[int(cls)]
p1, p2 = (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3]))
print('object_names is :', object_name, "Upper_left_coordinates:(" + str(p1[0]) + "," + str(
p1[1]) + "),Lower_right_coordinates(" + str(p2[0])
+ "," + str(p2[1]) + ")")
# 将坐标写进txt文本中
halcon = open('Coordinates.txt', mode='a')
halcon.writelines(str(p1[0]) + "," + str(p1[1]) + "," + str(p2[0]) + "," + str(p2[1]) + ",")
halcon.close()
采用pyinstaller打包。采用配置文件打包.spec,配置文件如下:
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['detect.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=['matplotlib.backends.backend_tkagg'],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
for d in a.datas:
if '_C.cp37-win_amd64' in d[0]:
a.datas.remove(d)
break
for d in a.datas:
if '_C.cp38-win_amd64.pyd' in d[0]:
a.datas.remove(d)
break
for d in a.datas:
if '_C_flatbuffer.cp38-win_amd64.pyd' in d[0]:
a.datas.remove(d)
break
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='detect',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir='C:\yolov5\Temp',
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
非python的用户文件pyinstaller 是不会打包的,需要添加,比如你的数据文件,外部系统配置文件等等,需要你放到程序中指定的位置上才行,所以,建议不要采用绝对路径的方式进行文件读写操作
--add-data
参数将这些文件包含进来,否则在运行时可能会出现找不到文件的错误。例如,如果您的 detect.py 中使用了一个名为 data.txt 的文件,那么您可以这样打包:
pyinstaller detect.py --add-data "data.txt;."
open('data.txt')
来打开文件,那么在打包后的程序中也应该使用 open('data.txt')
来访问文件。此外,如果您的 detect.py 中使用了绝对路径来访问文件,那么在打包后的程序中这些路径可能会发生变化,因此您需要注意修改这些路径。
解决 pyinstaller 打包时,包含的数据找不到
如有帮助,望采纳
https://blog.csdn.net/u012917013/article/details/125860885
a = Analysis( ... )
里面添加
a.datas += [
("/absolute/path/to/some.txt","txt_files/some.txt","DATA"),
("/absolute/path/to/some2.txt","txt_files/some2.txt","DATA"),
("/absolute/path/to/some3.txt","txt_files/some3.txt","DATA"),
]
然后代码里面这获取文件
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.environ.get("_MEIPASS2",os.path.abspath("."))
return os.path.join(base_path, relative_path)
...
txt_data = open(resource_path("txt_files/some.txt")).read()