You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无Python环境的PC运行导出可执行文件时出现Numpy错误

问题描述

在Visual Studio Code中运行程序一切正常;导出为可执行文件后本机运行也没问题,但在另一台无Python环境的Windows 10 22H2电脑上运行时,出现Numpy相关错误:

Traceback (most recent call last):   File "object_detector_from_camera.py", line 85, in <module> TypeError: __init__():
incompatible constructor arguments. The following argument types are supported:
1. mediapipe.python._framework_bindings.image.Image(image_format: mediapipe::ImageFormat_Format, data: numpy.ndarray[numpy.uint8])     
2. mediapipe.python._framework_bindings.image.Image(image_format: mediapipe::ImageFormat_Format, data: numpy.ndarray[numpy.uint16])     
3. mediapipe.python._framework_bindings.image.Image(image_format: mediapipe::ImageFormat_Format, data: numpy.ndarray[numpy.float32])  Invoked with: kwargs: image_format=<ImageFormat.SRGB: 1>, data=None

错误指向代码第85行:image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img)

使用的PyInstaller打包命令:
pyinstaller C:\Users\pc_test1\Desktop\schifo\object_detector_from_camera.py --noconsole --onefile

开发环境版本:

Python 3.12.1
mediapipe                 0.10.14
numpy                     2.0.0
opencv-contrib-python     4.10.0.84
opencv-python             4.10.0.84
pip                       23.2.1
pyinstaller               6.9.0

所有涉及电脑均为Windows 10 22H2系统,怀疑Build文件夹缺失文件,求解决思路。

附上代码:

import os
import cv2
import json
import numpy as np
import time
import sys
import imutils
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision


# 实现可视化目标检测结果的函数
import cv2
import numpy as np

MARGIN = 10  # 像素
ROW_SIZE = 10  # 像素
FONT_SIZE = 1
FONT_THICKNESS = 1
TEXT_COLOR = (255, 0, 0)  # 红色


def visualize(
    image,
    detection_result
) -> np.ndarray:
  """在输入图像上绘制边界框并返回
  Args:
    image: 输入RGB图像
    detection_result: 需要可视化的所有Detection实体列表
  Returns:
    带有边界框的图像
  """
  for detection in detection_result.detections:
    # 绘制边界框
    bbox = detection.bounding_box
    start_point = bbox.origin_x, bbox.origin_y
    end_point = bbox.origin_x + bbox.width, bbox.origin_y + bbox.height
    cv2.rectangle(image, start_point, end_point, TEXT_COLOR, 3)

    # 绘制标签和置信度
    category = detection.categories[0]
    category_name = category.category_name
    probability = round(category.score, 2)
    result_text = category_name + ' (' + str(probability) + ')'
    text_location = (MARGIN + bbox.origin_x,
                     ROW_SIZE + bbox.origin_y - (MARGIN + 10))
    cv2.putText(image, result_text, text_location, cv2.FONT_HERSHEY_PLAIN,
                FONT_SIZE, TEXT_COLOR, FONT_THICKNESS)

  return image

# 创建ObjectDetector对象
base_options = python.BaseOptions(model_asset_path='efficientdet_lite0.tflite')
options = vision.ObjectDetectorOptions(base_options=base_options,
                                       score_threshold=0.5)
detector = vision.ObjectDetector.create_from_options(options)


pTime = 0
cTime = 0

s = 0
# if len(sys.argv) > 1:
#     s = sys.argv[1]

print(s)
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    

cap = cv2.VideoCapture(s)

while True:
    success, img = cap.read()
    img = cv2.flip(img, 1)
    #imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    #image = mp.Image.create_from_file(img)
    image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img)
    detection_result = detector.detect(image)
    print(detection_result)
    image_copy = np.copy(image.numpy_view())
    annotated_image = visualize(image_copy, detection_result)
    rgb_annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
    #cv2.imshow("temp", rgb_annotated_image)
    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime
    annotated_image = imutils.resize(annotated_image, width=720)
    cv2.putText(annotated_image, str(int(fps)), (10,70), cv2.FONT_HERSHEY_COMPLEX, 3, (0,255,255), 3)
    cv2.imshow("window", annotated_image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
          break
解决思路
  • 排查摄像头读取失败问题:错误提示data=None,说明cap.read()返回的img是None,即目标电脑上摄像头读取失败。在代码中加入判断逻辑:

    while True:
        success, img = cap.read()
        if not success or img is None:
            print("无法读取摄像头画面")
            time.sleep(1)
            continue
        img = cv2.flip(img, 1)
        # 后续代码...
    

    同时确认目标电脑是否有摄像头、摄像头是否被占用或需要权限。

  • 修复色彩空间不匹配问题:OpenCV读取的图像是BGR格式,而mp.Image的SRGB格式需要RGB数据,必须添加格式转换:

    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    image = mp.Image(image_format=mp.ImageFormat.SRGB, data=imgRGB)
    
  • 完善PyInstaller打包配置:

    1. 改用--onedir模式打包(去掉--onefile),查看完整依赖文件,对比本机与目标机的运行差异,排查缺失库。
    2. 打包时手动指定隐藏依赖,确保numpy和mediapipe被完整打包:
      pyinstaller C:\Users\pc_test1\Desktop\schifo\object_detector_from_camera.py --noconsole --onefile --hidden-import numpy --hidden-import mediapipe
      
    3. 将efficientdet_lite0.tflite模型文件放到可执行文件同目录,确保程序能加载模型。
  • 降级numpy版本:numpy 2.0.0与mediapipe 0.10.14可能存在兼容性问题,降级到1.26.x版本后重新打包:

    pip install numpy==1.26.4
    

内容的提问来源于stack exchange,提问作者Noob_Testautomation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:58:10