【发布时间】:2020-11-05 18:19:27
【问题描述】:
我正在使用 TensorFlow 2.2.0(Python 3.8.3,在 Anaconda3 中)并且已经完成了对象检测模型的训练。我正在运行一个名为“detect_objects.py”的脚本,可以在下面的脚本中看到。我已经为 10 个测试图像指定了一个图像路径,以测试模型的训练效果。
#Import modules
import time
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1)
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2)
# Enable GPU dynamic memory allocation
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
#Specify directory where trained model is saved
PATH_TO_SAVED_MODEL = 'exported-models\my_model\saved_model'
print('Loading model...', end='')
start_time = time.time()
# Load saved model and build the detection function
detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL)
end_time = time.time()
elapsed_time = end_time - start_time
print('Done! Took {} seconds'.format(elapsed_time))
#Path to .pbtxt file
category_index = label_map_util.create_category_index_from_labelmap('annotations\label_map.pbtxt',use_display_name=True)
#Detect objects in images
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file path to the image
Returns:
uint8 numpy array with shape (img_height, img_width, 3)
"""
return np.array(Image.open(path))
#Specify path for test images
IMAGE_PATHS = 'images\evaluation_images'
for image_path in IMAGE_PATHS:
print('Running inference for {}... '.format(image_path), end='')
image_np = load_image_into_numpy_array(image_path)
# Things to try:
# Flip horizontally
# image_np = np.fliplr(image_np).copy()
# Convert image to grayscale
# image_np = np.tile(
# np.mean(image_np, 2, keepdims=True), (1, 1, 3)).astype(np.uint8)
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
input_tensor = tf.convert_to_tensor(image_np)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis, ...]
# input_tensor = np.expand_dims(image_np, 0)
detections = detect_fn(input_tensor)
# All outputs are batches tensors.
# Convert to numpy arrays, and take index [0] to remove the batch dimension.
# We're only interested in the first num_detections.
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_np_with_detections,
detections['detection_boxes'],
detections['detection_classes'],
detections['detection_scores'],
category_index,
use_normalized_coordinates=True,
max_boxes_to_draw=200,
min_score_thresh=.30,
agnostic_mode=False)
plt.figure()
plt.imshow(image_np_with_detections)
print('Done')
plt.show()
# sphinx_gallery_thumbnail_number = 2
产生以下错误:
Loading model...Done! Took 35.13338613510132 seconds
Running inference for i... Traceback (most recent call last):
File "detect_objects.py", line 64, in <module>
image_np = load_image_into_numpy_array(image_path)
File "detect_objects.py", line 55, in load_image_into_numpy_array
return np.array(Image.open(path))
File "C:\Users\user\pillow-8.0.1-py3.8-win-amd64.egg\PIL\Image.py", line 2891, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'i'
是什么导致了这个错误?我的代码有错误吗?
作为参考,这是错误中引用的Image.py 脚本中的第 2841 到 2898 行:
def open(fp, mode="r", formats=None):
"""
Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but
the file remains open and the actual image data is not read from
the file until you try to process the data (or call the
:py:meth:`~PIL.Image.Image.load` method). See
:py:func:`~PIL.Image.new`. See :ref:`file-handling`.
:param fp: A filename (string), pathlib.Path object or a file object.
The file object must implement ``file.read``,
``file.seek``, and ``file.tell`` methods,
and be opened in binary mode.
:param mode: The mode. If given, this argument must be "r".
:param formats: A list or tuple of formats to attempt to load the file in.
This can be used to restrict the set of formats checked.
Pass ``None`` to try all supported formats. You can print the set of
available formats by running ``python -m PIL`` or using
the :py:func:`PIL.features.pilinfo` function.
:returns: An :py:class:`~PIL.Image.Image` object.
:exception FileNotFoundError: If the file cannot be found.
:exception PIL.UnidentifiedImageError: If the image cannot be opened and
identified.
:exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
instance is used for ``fp``.
:exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
"""
if mode != "r":
raise ValueError(f"bad mode {repr(mode)}")
elif isinstance(fp, io.StringIO):
raise ValueError(
"StringIO cannot be used to open an image. "
"Binary data must be used instead."
)
if formats is None:
formats = ID
elif not isinstance(formats, (list, tuple)):
raise TypeError("formats must be a list or tuple")
exclusive_fp = False
filename = ""
if isinstance(fp, Path):
filename = str(fp.resolve())
elif isPath(fp):
filename = fp
if filename:
fp = builtins.open(filename, "rb")
exclusive_fp = True
try:
fp.seek(0)
except (AttributeError, io.UnsupportedOperation):
fp = io.BytesIO(fp.read())
exclusive_fp = True
【问题讨论】:
-
IMAGE_PATHS是一个字符串。用“for”遍历字符串意味着分别遍历每个字符。 -
@MichaelButscher 它应该指定一个目录。我在 Anaconda 提示符下工作,将“cd”命令设置为“images”的父文件夹。是否有其他方式来指示文件路径?
-
您可以将
IMAGE_PATHS设为只有一项(路径字符串)的列表。
标签: python tensorflow anaconda