opencv 尝试使用pyinstaller(Python)创建exe时出现“元组索引超出范围”错误

rryofs0p  于 2023-05-29  发布在  Python
关注(0)|答案(1)|浏览(188)

我正在尝试用opencv,mediapipe和时间模块创建一个手部跟踪器。当我在IDE中运行它时,它工作得很好,但是当我尝试使用以下pyinstaller命令将其转换为exe时:“pyinstaller -w -F HandTrackingProgram.py“,它说了一堆东西,在最后,给出了以下错误“IndexError:元组索引超出范围”。下面是我的代码:
代码如下:

import cv2
import mediapipe as mp
import time

cap = cv2.VideoCapture(0)
mpHands = mp.solutions.hands
hands = mpHands.Hands()
mpDraw = mp.solutions.drawing_utils

pTime = 0
cTime = 0

while True:
    success, img = cap.read()
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = hands.process(imgRGB)
    if results.multi_hand_landmarks:
        for handLms in results.multi_hand_landmarks:
            for id, lm in enumerate(handLms.landmark):
                h, w, c = img.shape
                cx, cy = int(lm.x*w), int(lm.y*h)
            mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)

    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime

    cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3)

    cv2.imshow("Image", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

我怀疑问题可能出在mediapipe库上,因为当我使用Python 3.11时,mediapipe不会安装。我用了3.10。Mediapipe成功安装,但现在,我面临这个问题。整个错误消息太长,看起来像垃圾邮件,所以这里有一个图像代替(这不是整个错误消息:enter image description here

更新:我能够转换成一个exe不知何故,但当我运行exe文件,我得到这个错误,“Traceback(最近调用最后):文件“nauru.py”,第7行,在文件“mediapipe\python\solutions\hands.py”,第114行,在init文件“mediapipe\python\solution_base.py”,第264行,在initFileNotFoundError:路径不存在。”

vsaztqbk

vsaztqbk1#

使用this answer中描述的方法,我设法解决了FileNotFoundError: The path does not exist问题。
您可以使用以下HandTrackingProgram.spec通过调用python -m PyInstaller HandTrackingProgram.spec来构建单文件exe:

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

def get_mediapipe_path():
    import mediapipe
    mediapipe_path = mediapipe.__path__[0]
    return mediapipe_path

a = Analysis(
    ['HandTrackingProgram.py'],
    pathex=[],
    binaries=[],
    datas=[],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

mediapipe_tree = Tree(get_mediapipe_path(), prefix='mediapipe', excludes=["*.pyc"])
a.datas += mediapipe_tree
a.binaries = filter(lambda x: 'mediapipe' not in x[0], a.binaries)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='HandTrackingProgram',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

编译后的exe工作得很好(从相机获取数据并跟踪手)。

  • 注意:* 我使用Python 3.9(mediapipe 0.9.0),但希望它也适用于Python 3.10。

相关问题