python找不到对象怎么办_Python ImportError:找不到'nvcuda.dll'

在尝试使用Tensorflow进行对象识别时遇到错误:ImportError:找不到'nvcuda.dll'。该错误通常是由于缺少CUDA驱动或者环境变量配置不正确导致的。解决方案包括安装CUDA驱动,并确保'nvcuda.dll'位于系统路径下的'C:WindowsSystem32'或其他指定目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我只想使用tensorflow从inception预训练模型进行对象识别&我使用以下代码:from __future__ import absolute_import

from __future__ import division

from __future__ import print_function

import argparse

import os.path

import re

import sys

import tarfile

import numpy as np

from six.moves import urllib

import tensorflow as tf

FLAGS = None

# pylint: disable=line-too-long

DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'

# pylint: enable=line-too-long

class NodeLookup(object):

def __init__(self,

label_lookup_path=None,

uid_lookup_path=None):

if not label_lookup_path:

label_lookup_path = os.path.join(

FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')

if not uid_lookup_path:

uid_lookup_path = os.path.join(

FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')

self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

def load(self, label_lookup_path, uid_lookup_path):

if not tf.gfile.Exists(uid_lookup_path):

tf.logging.fatal('File does not exist %s', uid_lookup_path)

if not tf.gfile.Exists(label_lookup_path):

tf.logging.fatal('File does not exist %s', label_lookup_path)

# Loads mapping from string UID to human-readable string

proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()

uid_to_human = {}

p = re.compile(r'[n\d]*[ \S,]*')

for line in proto_as_ascii_lines:

parsed_items = p.findall(line)

uid = parsed_items[0]

human_string = parsed_items[2]

uid_to_human[uid] = human_string

# Loads mapping from string UID to integer node ID.

node_id_to_uid = {}

proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()

for line in proto_as_ascii:

if line.startswith(' target_class:'):

target_class = int(line.split(': ')[1])

if line.startswith(' target_class_string:'):

target_class_string = line.split(': ')[1]

node_id_to_uid[target_class] = target_class_string[1:-2]

# Loads the final mapping of integer node ID to human-readable string

node_id_to_name = {}

for key, val in node_id_to_uid.items():

if val not in uid_to_human:

tf.logging.fatal('Failed to locate: %s', val)

name = uid_to_human[val]

node_id_to_name[key] = name

return node_id_to_name

def id_to_string(self, node_id):

if node_id not in self.node_lookup:

return ''

return self.node_lookup[node_id]

def create_graph():

# Creates graph from saved graph_def.pb.

with tf.gfile.FastGFile(os.path.join(

FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:

graph_def = tf.GraphDef()

graph_def.ParseFromString(f.read())

_ = tf.import_graph_def(graph_def, name='')

def run_inference_on_image(image):

if not tf.gfile.Exists(image):

tf.logging.fatal('File does not exist %s', image)

image_data = tf.gfile.FastGFile(image, 'rb').read()

# Creates graph from saved GraphDef.

create_graph()

with tf.Session() as sess:

softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')

predictions = sess.run(softmax_tensor,

{'DecodeJpeg/contents:0': image_data})

predictions = np.squeeze(predictions)

# Creates node ID --> English string lookup.

node_lookup = NodeLookup()

top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]

for node_id in top_k:

human_string = node_lookup.id_to_string(node_id)

score = predictions[node_id]

print('%s (score = %.5f)' % (human_string, score))

def maybe_download_and_extract():

"""Download and extract model tar file."""

dest_directory = FLAGS.model_dir

if not os.path.exists(dest_directory):

os.makedirs(dest_directory)

filename = DATA_URL.split('/')[-1]

filepath = os.path.join(dest_directory, filename)

if not os.path.exists(filepath):

def _progress(count, block_size, total_size):

sys.stdout.write('\r>> Downloading %s %.1f%%' % (

filename, float(count * block_size) / float(total_size) * 100.0))

sys.stdout.flush()

filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)

print()

statinfo = os.stat(filepath)

print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')

tarfile.open(filepath, 'r:gz').extractall(dest_directory)

def main(_):

maybe_download_and_extract()

image = (FLAGS.image_file if FLAGS.image_file else

os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))

run_inference_on_image(image)

if __name__ == '__main__':

parser = argparse.ArgumentParser()

parser.add_argument(

'--model_dir',

type=str,

default='/tmp/imagenet',

help="""\

Path to classify_image_graph_def.pb,

imagenet_synset_to_human_label_map.txt, and

imagenet_2012_challenge_label_map_proto.pbtxt.\

"""

)

parser.add_argument(

'--image_file',

type=str,

default='',

help='Absolute path to image file.'

)

parser.add_argument(

'--num_top_predictions',

type=int,

default=5,

help='Display this many predictions.'

)

FLAGS, unparsed = parser.parse_known_args()

tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

我从这个repo中找到这段代码,我通过在cmd“python”中给出命令来简单地运行它分类.py“然后它显示了这个错误Traceback (most recent call last):

File "C:\Users---\Python\Python36\lib\site-packages\tensorflow\python\platform\self_check.py", line 62, in preload_check

ctypes.WinDLL(build_info.nvcuda_dll_name)

File "C:\Users---\Python\Python36\lib\ctypes__init__.py", line 348, in init

self._handle = _dlopen(self._name, mode)

OSError: [WinError 126] The specified module could not be found

在处理上述异常时,发生了另一个异常:Traceback (most recent call last): File "obj_recog.py", line 41, in

import tensorflow as tf File "C:\Users---\Python\Python36\lib\site-packages\tensorflow__init__.py",

line 22, in

from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File

"C:\Users---\Python\Python36\lib\site-packages\tensorflow\python__init__.py",

line 49, in

from tensorflow.python import pywrap_tensorflow File "C:\Users---\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py",

line 30, in

self_check.preload_check() File "C:\Users---\Python\Python36\lib\site-packages\tensorflow\python\platform\self_check.py",

line 70, in preload_check

% build_info.nvcuda_dll_name) ImportError: Could not find 'nvcuda.dll'. TensorFlow requires that this DLL be installed in a

directory that is named in your %PATH% environment variable. Typically

it is installed in 'C:\Windows\System32'. If it is not present, ensure

that you have a CUDA-capable GPU with the correct driver installed.

import torch print(f"PyTorch版本: {torch.__version__}") print(f"CUDA可用: {torch.cuda.is_available()}") print(f"GPU数量: {torch.cuda.device_count()}") print(f"当前GPU: {torch.cuda.get_device_name(0)}") PyTorch版本: 2.0.1+cpu CUDA可用: False GPU数量: 0 --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[1], line 5 3 print(f"CUDA可用: {torch.cuda.is_available()}") 4 print(f"GPU数量: {torch.cuda.device_count()}") ----> 5 print(f"当前GPU: {torch.cuda.get_device_name(0)}") File ~\AppData\Roaming\Python\Python310\site-packages\torch\cuda\__init__.py:365, in get_device_name(device) 353 def get_device_name(device: Optional[_device_t] = None) -> str: 354 r"""Gets the name of a device. 355 356 Args: (...) 363 str: the name of the device 364 """ --> 365 return get_device_properties(device).name File ~\AppData\Roaming\Python\Python310\site-packages\torch\cuda\__init__.py:395, in get_device_properties(device) 385 def get_device_properties(device: _device_t) -> _CudaDeviceProperties: 386 r"""Gets the properties of a device. 387 388 Args: (...) 393 _CudaDeviceProperties: the properties of the device 394 """ --> 395 _lazy_init() # will define _get_device_properties 396 device = _get_device_index(device, optional=True) 397 if device < 0 or device >= device_count(): File ~\AppData\Roaming\Python\Python310\site-packages\torch\cuda\__init__.py:239, in _lazy_init() 235 raise RuntimeError( 236 "Cannot re-initialize CUDA in forked subprocess. To use CUDA with " 237 "multiprocessing, you must use the 'spawn' start method") 238 if not hasattr(torch._C, '_cuda_getDeviceCount'): --> 239 raise AssertionError("Torch not compiled with CUDA enabled") 240 if _cudart is None: 241 raise AssertionError( 242 "libcudart functions unavailable. It looks like you have a broken build?") AssertionError: Torch not compiled with CUDA enabled
最新发布
07-24
### TensorFlow 导入时出现 DLL 加载失败问题的解决方案 当遇到 `ImportError: DLL load failed while importing _pywrap_tensorflow_internal` 的错误时,通常是因为环境配置或依赖项缺失引起的。以下是可能的原因以及对应的解决办法: #### 1. **CPU 不兼容** 如果使用的 CPU 不支持 AVX 或 AVX2 指令集,则可能导致此问题。TensorFlow 高版本(1.5 及以上)仅支持具有 AVX2 指令集的 CPU[^2]。 - 如果设备为 Pentium 系列或其他低功耗处理器,建议尝试安装旧版 TensorFlow(如 TensorFlow 1.5)。可以通过以下命令完成安装: ```bash pip install tensorflow==1.5 ``` #### 2. **缺少必要的 Visual C++ Redistributable** 动态链接库 (DLL) 初始化例程失败可能是由于未正确安装 Microsoft Visual C++ Redistributable 库所致。该库提供了运行某些应用程序所需的组件[^3]。 - 前往微软官方网站下载并安装最新版本的 Visual Studio C++ Redistributable (`vc_redist.x64.exe`): - 下载地址:https://support.microsoft.com/zh-cn/help/2977003/the-latest-supported-visual-c-downloads[^4] #### 3. **Jupyter Notebook 和 IPython 环境冲突** 有时 Jupyter Notebook 中已有的包可能会与新安装的 TensorFlow 发生冲突。可以考虑卸载现有的 `ipython` 和 `jupyter` 并重新通过 Conda 安装它们[^1]。 - 卸载现有包: ```bash conda remove ipython jupyter ``` - 重新安装: ```bash conda install ipython jupyter ``` #### 4. **Python 版本不匹配** 确保 Python 版本与所选的 TensorFlow 版本相匹配。例如,TensorFlow 2.x 支持 Python 3.5 至 3.8,而更高版本的 Python 可能无法正常工作[^5]。 #### 5. **虚拟环境隔离** 创建一个新的虚拟环境来避免与其他项目发生依赖冲突。这有助于保持开发环境整洁并减少潜在问题的发生概率。 - 使用 Conda 创建虚拟环境: ```bash conda create -n tf_env python=3.7 conda activate tf_env pip install tensorflow ``` --- ### 总结 上述方法涵盖了多种常见原因及其对应解决方案。具体实施时可根据实际情况逐一排查。若仍存在问题,请提供完整的堆栈跟踪信息以便进一步分析。 ```python import tensorflow as tf print(tf.__version__) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值