我尝试通过遵循本教程来学习tensorflow
:https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10执行步骤2g后,我的代码在线显示,并且我必须检查它是否有错误。当我这样做时,我收到了很多错误,有些似乎没有必要(例如,显然没有定义“ os”)。我既查看了GitHub的“常见错误”部分,又查看了注释部分,但似乎没有人遇到与我相同的问题。在某些错误中,我也遵循了说明,但是没有任何效果。代码错误有点乱码,因此我将尽力在下面格式化它们。我对tensorflow
完全陌生,所以对我来说这完全是外国领土。任何帮助将非常感激。
代码:
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from object_detection.utils import ops as utils_ops
if StrictVersion(tf.__version__) < StrictVersion('1.9.0'):
raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!')
# This is needed to display the images.
%matplotlib inline
from utils import label_map_util
from utils import visualization_utils as vis_util
# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
opener = urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
tar_file = tarfile.open(MODEL_FILE)
for file in tar_file.getmembers():
file_name = os.path.basename(file.name)
if 'frozen_inference_graph.pb' in file_name:
tar_file.extract(file, os.getcwd())
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add the path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, ) ]
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)
def run_inference_for_single_image(image, graph):
with graph.as_default():
with tf.Session() as sess:
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in [
'num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks'
]:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
tensor_name)
if 'detection_masks' in tensor_dict:
# The following processing is only for single image
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(
detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
# Run inference
output_dict = sess.run(tensor_dict,
feed_dict={image_tensor: np.expand_dims(image, 0)})
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict[
'detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
return output_dict
for image_path in TEST_IMAGE_PATHS:
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
output_dict = run_inference_for_single_image(image_np, detection_graph)
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True,
line_thickness=8)
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np)
错误(其中许多是多余的):
ImportError Traceback (most recent call last)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
15 try:
---> 16 from . import multiarray
17 except ImportError as exc:
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\multiarray.py in <module>
11
---> 12 from . import overrides
13 from . import _multiarray_umath
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\overrides.py in <module>
5
----> 6 from numpy.core._multiarray_umath import (
7 add_docstring, implement_array_function, _get_implementing_args)
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-1-1e9eee4e6961> in <module>
----> 1 import numpy as np
2 import os
3 import six.moves.urllib as urllib
4 import sys
5 import tarfile
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\__init__.py in <module>
140 from . import _distributor_init
141
--> 142 from . import core
143 from .core import *
144 from . import compat
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
45 Original error was: %s
46 """ % (sys.executable, exc)
---> 47 raise ImportError(msg)
48 finally:
49 for envkey in env_added:
ImportError:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the multiarray numpy extension module failed. Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
(removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
1. Check that you are using the Python you expect (you're using c:\users\vfx\anaconda3\envs\tensorflow1\python.exe),
and that you have no directories in your PATH or PYTHONPATH that can
interfere with the Python and numpy versions you're trying to use.
2. If (1) looks fine, you can open a new issue at
https://github.com/numpy/numpy/issues. Please include details on:
- how you installed Python
- how you installed numpy
- your operating system
- whether or not you have multiple versions of Python installed
- if you built from source, your compiler versions and ideally a build log
Note: this error has many possible causes, so please don't comment on
an existing issue about this - open a new one instead.
Original error was: DLL load failed: The specified module could not be found.
ImportError Traceback (most recent call last)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
15 try:
---> 16 from . import multiarray
17 except ImportError as exc:
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\multiarray.py in <module>
11
---> 12 from . import overrides
13 from . import _multiarray_umath
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\overrides.py in <module>
5
----> 6 from numpy.core._multiarray_umath import (
7 add_docstring, implement_array_function, _get_implementing_args)
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-2-0f0a85121700> in <module>
1 # This is needed to display the images.
----> 2 get_ipython().run_line_magic('matplotlib', 'inline')
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2285 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2286 with self.builtin_trap:
-> 2287 result = fn(*args,**kwargs)
2288 return result
2289
<c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\decorator.py:decorator-gen-108> in matplotlib(self, line)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\magics\pylab.py in matplotlib(self, line)
97 print("Available matplotlib backends: %s" % backends_list)
98 else:
---> 99 gui, backend = self.shell.enable_matplotlib(args.gui)
100 self._show_matplotlib_backend(args.gui, backend)
101
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\interactiveshell.py in enable_matplotlib(self, gui)
3341 """
3342 from IPython.core import pylabtools as pt
-> 3343 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3344
3345 if gui != 'inline':
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\pylabtools.py in find_gui_and_backend(gui, gui_select)
274 """
275
--> 276 import matplotlib
277
278 if gui and gui != 'auto':
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\matplotlib\__init__.py in <module>
139 # cbook must import matplotlib only within function
140 # definitions, so it is safe to import from it here.
--> 141 from . import cbook, rcsetup
142 from matplotlib.cbook import (
143 MatplotlibDeprecationWarning, dedent, get_label, sanitize_sequence)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\matplotlib\cbook\__init__.py in <module>
31 from weakref import WeakMethod
32
---> 33 import numpy as np
34
35 import matplotlib
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\__init__.py in <module>
140 from . import _distributor_init
141
--> 142 from . import core
143 from .core import *
144 from . import compat
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
45 Original error was: %s
46 """ % (sys.executable, exc)
---> 47 raise ImportError(msg)
48 finally:
49 for envkey in env_added:
ImportError:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the multiarray numpy extension module failed. Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
(removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
1. Check that you are using the Python you expect (you're using c:\users\vfx\anaconda3\envs\tensorflow1\python.exe),
and that you have no directories in your PATH or PYTHONPATH that can
interfere with the Python and numpy versions you're trying to use.
2. If (1) looks fine, you can open a new issue at
https://github.com/numpy/numpy/issues. Please include details on:
- how you installed Python
- how you installed numpy
- your operating system
- whether or not you have multiple versions of Python installed
- if you built from source, your compiler versions and ideally a build log
Note: this error has many possible causes, so please don't comment on
an existing issue about this - open a new one instead.
The original error was: DLL load failed: The specified module could not be found.
ImportError Traceback (most recent call last)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
15 try:
---> 16 from . import multiarray
17 except ImportError as exc:
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\multiarray.py in <module>
11
---> 12 from . import overrides
13 from . import _multiarray_umath
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\overrides.py in <module>
5
----> 6 from numpy.core._multiarray_umath import (
7 add_docstring, implement_array_function, _get_implementing_args)
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-54-aa270cd948af> in <module>
----> 1 from utils import label_map_util
2
3 from utils import visualization_utils as vis_util
C:\tensorflow1\models\research\object_detection\utils\label_map_util.py in <module>
17 import logging
18
---> 19 import tensorflow as tf
20 from google.protobuf import text_format
21 from object_detection.protos import string_int_label_map_pb2
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\__init__.py in <module>
22
23 # pylint: disable=g-bad-import-order
---> 24 from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
25
26 from tensorflow._api.v1 import app
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\__init__.py in <module>
45 # pylint: disable=wildcard-import,g-bad-import-order,g-import-not-at-top
46
---> 47 import numpy as np
48
49 from tensorflow.python import pywrap_tensorflow
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\__init__.py in <module>
140 from . import _distributor_init
141
--> 142 from . import core
143 from .core import *
144 from . import compat
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
45 Original error was: %s
46 """ % (sys.executable, exc)
---> 47 raise ImportError(msg)
48 finally:
49 for envkey in env_added:
ImportError:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the multiarray numpy extension module failed. Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
(removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
1. Check that you are using the Python you expect (you're using c:\users\vfx\anaconda3\envs\tensorflow1\python.exe),
and that you have no directories in your PATH or PYTHONPATH that can
interfere with the Python and numpy versions you're trying to use.
2. If (1) looks fine, you can open a new issue at
https://github.com/numpy/numpy/issues. Please include details on:
- how you installed Python
- how you installed numpy
- your operating system
- whether or not you have multiple versions of Python installed
- if you built from source, your compiler versions and ideally a build log
Note: this error has many possible causes, so please don't comment on
an existing issue about this - open a new one instead.
Original error was: DLL load failed: The specified module could not be found.
NameError Traceback (most recent call last)
<ipython-input-3-8920c723e613> in <module>
8
9 # List of the strings that is used to add correct label for each box.
---> 10 PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
NameError: name 'os' is not defined
NameError Traceback (most recent call last)
<ipython-input-4-f921d2932261> in <module>
----> 1 opener = urllib.request.URLopener()
2 opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
3 tar_file = tarfile.open(MODEL_FILE)
4 for file in tar_file.getmembers():
5 file_name = os.path.basename(file.name)
NameError: name 'urllib' is not defined
NameError Traceback (most recent call last)
<ipython-input-5-d55b98fd5a78> in <module>
----> 1 detection_graph = tf.Graph()
2 with detection_graph.as_default():
3 od_graph_def = tf.GraphDef()
4 with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
5 serialized_graph = fid.read()
NameError: name 'tf' is not defined
NameError Traceback (most recent call last)
<ipython-input-6-d9bd1cb2606d> in <module>
----> 1 category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
NameError: name 'label_map_util' is not defined
NameError Traceback (most recent call last)
<ipython-input-12-9d222f84ff65> in <module>
4 # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
5 PATH_TO_TEST_IMAGES_DIR = 'test_images'
----> 6 TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, ) ]
7
8 # Size, in inches, of the output images.
<ipython-input-12-9d222f84ff65> in <listcomp>(.0)
4 # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
5 PATH_TO_TEST_IMAGES_DIR = 'test_images'
----> 6 TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, ) ]
7
8 # Size, in inches, of the output images.
NameError: name 'os' is not defined
NameError Traceback (most recent call last)
<ipython-input-10-b19082c2666b> in <module>
----> 1 for image_path in TEST_IMAGE_PATHS:
2 image = Image.open(image_path)
3 # the array based representation of the image will be used later in order to prepare the
4 # result image with boxes and labels on it.
5 image_np = load_image_into_numpy_array(image)
NameError: name 'TEST_IMAGE_PATHS' is not defined