写了一个根据不同IP地址在图片上写入不同网络环境信息,并设置成桌面的程序。用pyinstaller打包单个exe后,程序运行无法调用图片文件
第一次发生错误是因为调用了本地图片文件路径,后来改成了相对路径,获取了程序运行的临时目录后,还是无法读取图片
具体代码如下:
import cv2
import os
import sys
from IPy import IP
import socket
Base_Dir = os.path.dirname(os.path.abspath(__file__))
res = socket.gethostbyname(socket.gethostname())
if IP(res) in IP('38.192.0.1/13',make_net=1):
bk_img = cv2.imread(os.path.join(Base_Dir, 'background1.jpg'))
elif IP(res) in IP('15.240.0.1/13',make_net=1):
bk_img = cv2.imread(os.path.join(Base_Dir, 'background2.jpg'))
elif IP(res) in IP('10.244.0.1/15',make_net=1):
bk_img = cv2.imread(os.path.join(Base_Dir, 'background3.jpg'))
else :
bk_img = cv2.imread(os.path.join(Base_Dir, 'background.jpg'))
cv2.putText(bk_img, res, (560,250), cv2.FONT_HERSHEY_DUPLEX, 0.9, (0, 0, 0), 1, cv2.LINE_AA)
cv2.imshow(os.path.join(Base_Dir, 'add_text.jpg'), bk_img)
cv2.waitKey(2)
cv2.imwrite(os.path.join(Base_Dir, 'add_text.jpg'), bk_img)
cv2.startWindowThread()
import ctypes
ctypes.windll.user32.SystemParametersInfoW(20, 0, os.path.join(Base_Dir, 'add_text.jpg'), 0)
报错信息:
[21856] Failed to execute script 'add2' due to unhandled exception!
PS C:\Users\lk822\Desktop\wallpaper\dist> C:\Users\lk822\Desktop\wallpaper\dist\add2.exe
192.168.31.15
[ WARN:0@0.045] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('C:\Users\lk822\AppData\Local\Temp\_MEI144282\background.jpg'): can't open/read file: check file path/integrity
Traceback (most recent call last):
File "add2.py", line 26, in
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
[22412] Failed to execute script 'add2' due to unhandled exception!
以为是读取图片路径问题,写了相对路径获取运行路径加文件名的方式,还是不行。
打包单个exe的话,是不是获取程序运行的临时目录有问题,还是opencv有问题。