Tensorflow numpy 图像重塑 [灰度图像]

7

我正在尝试在jupyter笔记本中执行Tensorflow的“object_detection_tutorial.py”,并使用我训练好的神经网络数据,但是它抛出了一个ValueError。上述文件是Sentdex在Youtube上关于目标检测的tensorflow教程的一部分。

您可以在此处找到它:(https://www.youtube.com/watch?v=srPndLNMMpk&list=PLQVvvaa0QuDcNK5GeCQnxYnSSaar2tpku&index=6)

我的图像大小为490x704。这将导致344960个数组。

但它说:ValueError: cannot reshape array of size 344960 into shape (490,704,3)

我做错了什么?

代码:

导入

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

环境设置

# This is needed to display the images.
%matplotlib inline

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

对象检测引入

from utils import label_map_util

from utils import visualization_utils as vis_util

变量

# What model to download.
MODEL_NAME = 'shard_graph'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = 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('training', 'object-detection.pbtxt')

NUM_CLASSES = 90

将(冻结的)Tensorflow模型加载到内存中。

detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')

加载标签映射

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

辅助代码

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 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, 'frame_{}.png'.format(i)) for i in range(0, 2) ]

# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)

-

with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
    # Definite input and output Tensors for detection_graph
    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
    # Each box represents a part of the image where a particular object was detected.
    detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
    detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
    num_detections = detection_graph.get_tensor_by_name('num_detections:0')
    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.
      (boxes, scores, classes, num) = sess.run(
          [detection_boxes, detection_scores, detection_classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})
      # Visualization of the results of a detection.
      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=8)
      plt.figure(figsize=IMAGE_SIZE)
      plt.imshow(image_np)

脚本的最后一部分抛出了错误:
----------------------------------------------------------------------
ValueError                           Traceback (most recent call last)
<ipython-input-62-7493eea60222> in <module>()
     14       # the array based representation of the image will be used later in order to prepare the
     15       # result image with boxes and labels on it.
---> 16       image_np = load_image_into_numpy_array(image)
     17       # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
     18       image_np_expanded = np.expand_dims(image_np, axis=0)

<ipython-input-60-af094dcdd84a> in load_image_into_numpy_array(image)
      2   (im_width, im_height) = image.size
      3   return np.array(image.getdata()).reshape(
----> 4       (im_height, im_width, 3)).astype(np.uint8)

ValueError: cannot reshape array of size 344960 into shape (490,704,3)

编辑:

因此我更改了此函数中的最后一行:

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)

to:

(im_height, im_width)).astype(np.uint8)

之前的ValueError问题已解决。但是现在出现了另一个与数组格式相关的ValueError错误:

----------------------------------------------------------------------
ValueError                           Traceback (most recent call last)
<ipython-input-107-7493eea60222> in <module>()
     20       (boxes, scores, classes, num) = sess.run(
     21           [detection_boxes, detection_scores, detection_classes, num_detections],
---> 22           feed_dict={image_tensor: image_np_expanded})
     23       # Visualization of the results of a detection.
     24       vis_util.visualize_boxes_and_labels_on_image_array(

~/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    898     try:
    899       result = self._run(None, fetches, feed_dict, options_ptr,
--> 900                          run_metadata_ptr)
    901       if run_metadata:
    902         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1109                              'which has shape %r' %
   1110                              (np_val.shape, subfeed_t.name,
-> 1111                               str(subfeed_t.get_shape())))
   1112           if not self.graph.is_feedable(subfeed_t):
   1113             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (1, 490, 704) for Tensor 'image_tensor:0', which has shape '(?, ?, ?, 3)'

这是否意味着这个TensorFlow模型不适用于灰度图像?有没有办法让它工作?

解决方案

感谢Matan Hugi,现在它可以正常工作了。我所需要做的就是将这个函数更改为:

def load_image_into_numpy_array(image):
    # The function supports only grayscale images
    last_axis = -1
    dim_to_repeat = 2
    repeats = 3
    grscale_img_3dims = np.expand_dims(image, last_axis)
    training_image = np.repeat(grscale_img_3dims, repeats, dim_to_repeat).astype('uint8')
    assert len(training_image.shape) == 3
    assert training_image.shape[-1] == 3
    return training_image

1
可能是模型期望一个 RGB 图像,但你使用了灰度图像作为输入? - sietschie
是的,事实上就是这样。我没有考虑到它。 - Artur Müller Romanov
1
你可以将 reshape(im_height, im_width, 3) 改为 reshape(im_height, im_width) - MatthewScarpino
谢谢,我发现我可以将这个参数从3改为1或者直接删除它。问题解决了。谢谢大家。 - Artur Müller Romanov
2
我认为这个错误发生是因为你的网络期望一个具有3个通道的输入。这就是为什么我建议将你的图像转换为RGB格式。 - sietschie
显示剩余3条评论
1个回答

9

Tensorflow期望输入的格式为NHWC,即(批次数,高度,宽度,通道数)。

步骤1 - 添加最后一个维度:

last_axis = -1
grscale_img_3dims = np.expand_dims(image, last_axis)

步骤 2 - 将最后一个尺寸重复 3 次:
dim_to_repeat = 2
repeats = 3
np.repeat(grscale_img_3dims, repeats, dim_to_repeat)

所以您的函数应该是:

def load_image_into_numpy_array(image):
    # The function supports only grayscale images
    assert len(image.shape) == 2, "Not a grayscale input image" 
    last_axis = -1
    dim_to_repeat = 2
    repeats = 3
    grscale_img_3dims = np.expand_dims(image, last_axis)
    training_image = np.repeat(grscale_img_3dims, repeats, dim_to_repeat).astype('uint8')
    assert len(training_image.shape) == 3
    assert training_image.shape[-1] == 3
    return training_image

2
第一行代码 assert len(image.shape) == 2, "Not a grayscale input image" 给我报错了。当我把它删掉后,程序就可以正常运行了。谢谢! - Artur Müller Romanov
重点是灰度可以是 len(image.shape)== 2 或 len(image.shape)== 3,其中最后一个维度的长度为1,这在此答案中没有得到处理。 - ikamen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接