【问题标题】:Pyinstaller .exe cannot find _tiffile module - Loading of some compressed images will be very slowPyinstaller .exe 找不到 _tiffile 模块 - 加载一些压缩图像会很慢
【发布时间】:2017-03-09 12:46:53
【问题描述】:

当我从 Pyinstaller 运行我的代码时,tiff 阅读器工作正常。使用 Pyinstaller 冻结后,我收到以下警告:

UserWarning: ImportError: No module named '_tifffile'. Loading of some compressed images will be very slow. Tifffile.c can be obtained at http://www.lfd.uci.edu/~gohlke

果然,以前需要几秒钟才能加载到 numpy 数组中的 tiff 文件现在可能需要几分钟。

这是我的代码的简化形式,用于解决问题。如果您加载像 this one 这样的示例 tiff,它应该可以快速加载而不会出现问题。

如果您使用C:\Python35\python.exe C:\Python35\Scripts\pyinstaller.exe --additional-hooks-dir=. --clean --win-private-assemblies tiffile_problems.py,您应该在运行时获得一个带有上述错误消息的功能性.exe。当您尝试加载相同的 tiff 时,现在需要更长的时间。

tiffile_problems.py

#!/usr/bin/env python3

import os
import sys
import traceback
import numpy as np
import matplotlib.pyplot as plt

from PyQt4.QtGui import *
from PyQt4.QtCore import *

sys.path.append('..')

from MBE_for_SO.util import fileloader, fileconverter

class NotConvertedError(Exception):
  pass

class FileAlreadyInProjectError(Exception):
  def __init__(self, filename):
    self.filename = filename

class Widget(QWidget):
  def __init__(self, project, parent=None):
    super(Widget, self).__init__(parent)

    if not project:
        self.setup_ui()
        return

  def setup_ui(self):
    vbox = QVBoxLayout()

    ## Related to importing Raws
    self.setWindowTitle('Import Raw File')

    #vbox.addWidget(QLabel('Set the size all data are to be rescaled to'))

    grid = QGridLayout()

    vbox.addLayout(grid)
    vbox.addStretch()

    self.setLayout(vbox)
    self.resize(400, 220)

    self.listview = QListView()
    self.listview.setStyleSheet('QListView::item { height: 26px; }')
    self.listview.setSelectionMode(QAbstractItemView.NoSelection)
    vbox.addWidget(self.listview)

    hbox = QVBoxLayout()
    pb = QPushButton('New Video')
    pb.clicked.connect(self.new_video)
    hbox.addWidget(pb)

    vbox.addLayout(hbox)
    vbox.addStretch()
    self.setLayout(vbox)


  def convert_tif(self, filename):
    path = os.path.splitext(os.path.basename(filename))[0] + '.npy'
    #path = os.path.join(self.project.path, path)

    progress = QProgressDialog('Converting tif to npy...', 'Abort', 0, 100, self)
    progress.setAutoClose(True)
    progress.setMinimumDuration(0)
    progress.setValue(0)

    def callback(value):
      progress.setValue(int(value * 100))
      QApplication.processEvents()

    try:
      fileconverter.tif2npy(filename, path, callback)
      print('Tifffile saved to wherever this script is')
    except:
      # qtutil.critical('Converting tiff to npy failed.')
      progress.close()
    return path

  def to_npy(self, filename):
    if filename.endswith('.raw'):
      print('No raws allowed')
      #filename = self.convert_raw(filename)
    elif filename.endswith('.tif'):
      filename = self.convert_tif(filename)
    else:
      raise fileloader.UnknownFileFormatError()
    return filename

  def import_file(self, filename):
    if not filename.endswith('.npy'):
      new_filename = self.to_npy(filename)
      if not new_filename:
        raise NotConvertedError()
      else:
        filename = new_filename

    return filename

  def import_files(self, filenames):
    for filename in filenames:
      try:
        filename = self.import_file(filename)
      except NotConvertedError:
        # qtutil.warning('Skipping file \'{}\' since not converted.'.format(filename))
        print('Skipping file \'{}\' since not converted.'.format(filename))
      except FileAlreadyInProjectError as e:
        # qtutil.warning('Skipping file \'{}\' since already in project.'.format(e.filename))
        print('Skipping file \'{}\' since already in project.'.format(e.filename))
      except:
        # qtutil.critical('Import of \'{}\' failed:\n'.format(filename) +\
        #   traceback.format_exc())
        print('Import of \'{}\' failed:\n'.format(filename) + traceback.format_exc())
      # else:
      #   self.listview.model().appendRow(QStandardItem(filename))

  def new_video(self):
    filenames = QFileDialog.getOpenFileNames(
      self, 'Load images', QSettings().value('last_load_data_path'),
      'Video files (*.npy *.tif *.raw)')
    if not filenames:
      return
    QSettings().setValue('last_load_data_path', os.path.dirname(filenames[0]))
    self.import_files(filenames)

class MyPlugin:
  def __init__(self, project):
    self.name = 'Import video files'
    self.widget = Widget(project)

  def run(self):
    pass

if __name__ == '__main__':
  app = QApplication(sys.argv)
  app.aboutToQuit.connect(app.deleteLater)
  w = QMainWindow()
  w.setCentralWidget(Widget(None))
  w.show()
  app.exec_()
  sys.exit()

fileconverter.py

#!/usr/bin/env python3

import os
import numpy as np

import tifffile as tiff

class ConvertError(Exception):
  pass

def tif2npy(filename_from, filename_to, progress_callback):
  with tiff.TiffFile(filename_from) as tif:
    w, h = tif[0].shape
    shape = len(tif), w, h
    np.save(filename_to, np.empty(shape, tif[0].dtype))
    fp = np.load(filename_to, mmap_mode='r+')
    for i, page in enumerate(tif):
      progress_callback(i / float(shape[0]-1))
      fp[i] = page.asarray()

def raw2npy(filename_from, filename_to, dtype, width, height,
  num_channels, channel, progress_callback):
    fp = np.memmap(filename_from, dtype, 'r')
    frame_size = width * height * num_channels
    if len(fp) % frame_size:
      raise ConvertError()
    num_frames = len(fp) / frame_size
    fp = np.memmap(filename_from, dtype, 'r',
      shape=(num_frames, width, height, num_channels))
    np.save(filename_to, np.empty((num_frames, width, height), dtype))
    fp_to = np.load(filename_to, mmap_mode='r+')
    for i, frame in enumerate(fp):
      progress_callback(i / float(len(fp)-1))
      fp_to[i] = frame[:,:,channel-1]

fileloader.py

#!/usr/bin/env python3

import numpy as np

class UnknownFileFormatError(Exception):
  pass

def load_npy(filename):
  frames = np.load(filename)
  # frames[np.isnan(frames)] = 0
  return frames

def load_file(filename):
  if filename.endswith('.npy'):
    frames = load_npy(filename)
  else:
    raise UnknownFileFormatError()
  return frames

def load_reference_frame_npy(filename, offset):
  frames_mmap = np.load(filename, mmap_mode='c')
  if frames_mmap is None:
    return None
  frame = np.array(frames_mmap[offset])
  frame[np.isnan(frame)] = 0
  frame = frame.swapaxes(0, 1)
  if frame.ndim == 2:
    frame = frame[:, ::-1]
  elif frame.ndim == 3:
    frame = frame[:, ::-1, :]
  return frame

def load_reference_frame(filename, offset=0):
  if filename.endswith('.npy'):
    frame = load_reference_frame_npy(filename, offset)
  else:
    raise UnknownFileFormatError()
  return frame

为什么?我该如何解决这个问题?我找到了tifffile.py, tifffile.cpython-35.pyc, tifffile.c 并将它们全部放在与.exe 相同的目录中。没有效果。 _tifffile.cp35-win_amd64.pyd 由 pyinstaller 创建并放置在与 .exe 相同的目录中。我不知道我还有什么其他选择。

tifffile_problems.spec

# -*- mode: python -*-

block_cipher = None


a = Analysis(['tiffile_problems.py'],
             pathex=['C:\\Users\\Cornelis\\PycharmProjects\\tester\\MBE_for_SO'],
             binaries=None,
             datas=None,
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=True,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='tiffile_problems',
          debug=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='tiffile_problems')

使用C:\Python35\python.exe C:\Python35\Scripts\pyinstaller.exe --additional-hooks-dir=. --clean --win-private-assemblies --onefile tiffile_problems.py时的tiffile.spec

# -*- mode: python -*-

block_cipher = None


a = Analysis(['tiffile_problems.py'],
             pathex=['C:\\Users\\Cornelis\\PycharmProjects\\tester\\MBE_for_SO'],
             binaries=None,
             datas=None,
             hiddenimports=[],
             hookspath=['.'],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=True,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='tiffile_problems',
          debug=False,
          strip=False,
          upx=True,
          console=True )

【问题讨论】:

    标签: python-3.x numpy tiff pyinstaller


    【解决方案1】:

    我认为 muggy 对他的怪异问题是正确的,__package__ 导致了这里的问题。我还没有找到修复的确切原因,但这似乎可以使用pyinstaller 的最新更新来解决。检查您的版本:

    → pyinstaller --version 3.2.1

    并升级

    → pip3 install --upgrade pyinstaller

    此更新仅在 2017 年 1 月 15 日进行,因此当您最初询问时这不会有帮助,但现在确实有帮助。

    【讨论】:

      【解决方案2】:

      实际上,我只是在网上浏览时通过 upwork 看到了这一点,并决定玩一玩。

      kazemakase一开始就走对了,正常运行时,__package__为None,而当它打包的__package__设置为tifffile并执行第一个条件时,就变成相对于模块tifffile了。

      if __package__:
          from . import _tifffile
      else:
          import _tifffile
      

      我只是手动将 tifffile 转换为模块,方法是在站点包中创建一个 tifffile 文件夹,在新文件夹中创建一个空的 __init__.py 文件,将站点包中的 tifffile.py、_tifffile.pyd 放入 tifffile 文件夹并更改导入语句,诚然在一个简单的骨架中。

      import tifffile.tifffile as tiff
      

      我不知道这是否有助于您的整个项目。并且应该注意我最初使用http://www.lfd.uci.edu/~gohlke/pythonlibs/ 的轮子来安装以节省编译步骤,因此您的里程可能会有所不同。我最初在 2.7 上完成了上述操作,但从我能够做的一些测试来看,它似乎在 3.5 上也能正常工作。当我从最初生成的文件进行测试时,不需要在 .spec 文件中添加任何内容。

      【讨论】:

      • 所以我确实想验证您的答案。但是,我首先尝试了 aconz2 的简单解决方案并且它有效(也从 gohike 轮卸载并重新安装了 tifffile)。现在,当我尝试恢复到以前的 pyinstaller 版本(3.2)时,我无法复制错误!它只是固定并保持固定!很奇怪。这意味着我无法测试您的答案是否有效,因为我不想深入研究我是否进行了其他一些偶然的更改,因为我很高兴它现在有效。无论哪种方式,我都会给你一个 +1,因为你可能比其他任何人都更正确地解释了错误的来源。
      • 没有问题.. 我怀疑您无论如何都无法重新测试,因为您已经升级了 setuptools/packaging,而这就是底层修复所在。
      【解决方案3】:

      通过检查代码,tifffile.py 似乎正在寻找一个名为 _tifffile 的模块,这可能是编译后的 C 扩展名的预期名称:

      try:
          if __package__:
              from . import _tifffile
          else:
              import _tifffile
      except ImportError:
          warnings.warn(
              "ImportError: No module named '_tifffile'. "
              "Loading of some compressed images will be very slow. "
              "Tifffile.c can be obtained at http://www.lfd.uci.edu/~gohlke/")
      

      tifffile.cpython-35.pyc 只是从tiffile.py 生成的字节码。你不需要为那个而烦恼。

      单独的.c 文件也无济于事。它需要被编译以创建一个可用的 Python 扩展,需要将其命名为 _tiffile.cp35-win_amd64.pyd(可能因您的系统和 Python 版本/安装而异),以便 import _tifffile 使用它。

      如果您以前没有这样做,编译可能是一项艰巨的任务。如果您觉得自己能胜任,Python documentation 可以帮助您入门。您将需要 same Compiler 和编译您的 Python 版本时使用的设置。

      但是,可能有更简单的解决方案。如果您的代码在冻结之前运行良好,那么您很可能已在系统上正确安装了已编译的扩展。 Pyinstaller 可能会错过它,因为它可以找到tifffile.py 并感到满意。在您的 Python 目录中查找正确的 .pyd 文件,看看您是否可以修改为您的项目创建的 .spec file Pyinstaller,您在其中指定包含 .pyd 文件。

      【讨论】:

      • 我的代码在冻结之前没有任何问题。 Tiff 文件加载又快又好。 _tifffile.cp35-win_amd64.pyd 是由 pyinstaller 创建的,我可以在包含 .exe 的目录中找到它。我已阅读您的链接,但我不确定如何将 _tifffile.cp35-win_amd64.pyd 包含到 .spec 中。我已将我的 .spec 添加到问题中
      • 我确实尝试将 datas= [ ('_tifffile.cp35-win_amd64.pyd' ) ] 作为分析规范中的一个字段。但是当我运行 pyinstaler 时,我注意到规范恢复到原来的样子。
      • ok nvm 我确实设法修改了规范以包含 .pyd 文件。但正如我所料,这没有什么区别,因为默认情况下该文件已经放置在包含 .exe 的目录中。这自然让我想知道这是怎么回事?如果 .c 文件已经编译并且正确,为什么不使用 import _tifffile 导入它?
      • 我在这里有点猜测:也许 pyinstaller 没有正确获取模块搜索路径,或者在启动生成的 .exe 时工作目录设置不正确。别的,我在你的 .spec 中注意到exclude_binaries=True。我不知道这个选项应该做什么,但听起来很可疑。请尝试将其设置为False。如果失败,您可以尝试的其他方法是使用 --onefile 运行 pyinstaller 以将所有内容捆绑到 .exe 中。
      • 当我这样做时,我得到了一个新的 .exe,它似乎是 dist 中的副本(比放置原始文件的 dist/tiffile_problems 高一级。这还不是全部。.exe 不起作用现在。它刚刚关闭。当我尝试用 cmd 打开它时,我得到“加载 Python DLL 时出错:C:\Users\Cornelis\AppData\Local\Temp_MEI108522\python35.dll(错误代码 126)”不知道为什么它必须在那里寻找 dll,因为它与 .exe 位于同一目录中。
      【解决方案4】:

      安装:

      ->如果使用 conda,conda install tifffile -c conda-forge

      -> 否则,pip install tifffile

      【讨论】:

        猜你喜欢
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-28
        • 2021-12-05
        • 2021-03-08
        • 2012-07-17
        • 1970-01-01
        相关资源
        最近更新 更多