tensorflow / tensorflow/models

ValueError: 'images' must have either 3 or 4 dimensions.

Open
#9,544 13 comments 0 reactions 3 assignees View on GitHub

@pkulzc is already working on this.

Since Dec 10, 2020.

models:research:odapi type:support
Dominant language
Python
Stars
77.7k
Forks
44.8k
PR merge metrics
No merged PRs in 30d

Description

I'm trying to run the following code on a jupyter notebook:

while True:
ret, frame = cap.read()
image_np = np.array(frame)

input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor)

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)

label_id_offset = 1
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']+label_id_offset,
            detections['detection_scores'],
            category_index,
            use_normalized_coordinates=True,
            max_boxes_to_draw=5,
            min_score_thresh=.5,
            agnostic_mode=False)

cv2.imshow('object detection',  cv2.resize(image_np_with_detections, (640, 480)))

if cv2.waitKey(1) & 0xFF == ord('q'):
    cap.release()
    break

And getting the following error:

ValueError Traceback (most recent call last)
in
4
5 input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
----> 6 detections = detect_fn(input_tensor)
7
8 num_detections = int(detections.pop('num_detections'))

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\eager\def_function.py in call(self, *args, **kwds)
778 else:
779 compiler = "nonXla"
--> 780 result = self._call(*args, **kwds)
781
782 new_tracing_count = self._get_tracing_count()

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds)
812 # In this case we have not created variables on the first call. So we can
813 # run the first trace but we should fail if variables are created.
--> 814 results = self._stateful_fn(*args, **kwds)
815 if self._created_variables:
816 raise ValueError("Creating variables on a non-first call to a function"

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\eager\function.py in call(self, *args, **kwargs)
2826 """Calls a graph function specialized to the inputs."""
2827 with self._lock:
-> 2828 graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
2829 return graph_function._filtered_call(args, kwargs) # pylint: disable=protected-access
2830

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\eager\function.py in _maybe_define_function(self, args, kwargs)
3211
3212 self._function_cache.missed.add(call_context_key)
-> 3213 graph_function = self._create_graph_function(args, kwargs)
3214 self._function_cache.primary[cache_key] = graph_function
3215 return graph_function, args, kwargs

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
3073 arg_names=arg_names,
3074 override_flat_arg_shapes=override_flat_arg_shapes,
-> 3075 capture_by_value=self._capture_by_value),
3076 self._function_attributes,
3077 function_spec=self.function_spec,

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
984 _, original_func = tf_decorator.unwrap(python_func)
985
--> 986 func_outputs = python_func(*func_args, **func_kwargs)
987
988 # invariant: func_outputs contains only Tensors, CompositeTensors,

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\eager\def_function.py in wrapped_fn(*args, **kwds)
598 # wrapped allows AutoGraph to swap in a converted function. We give
599 # the function a weak reference to itself to avoid a reference cycle.
--> 600 return weak_wrapped_fn().wrapped(*args, **kwds)
601 weak_wrapped_fn = weakref.ref(wrapped_fn)
602

c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\framework\func_graph.py in wrapper(*args, **kwargs)
971 except Exception as e: # pylint:disable=broad-except
972 if hasattr(e, "ag_error_metadata"):
--> 973 raise e.ag_error_metadata.to_exception(e)
974 else:
975 raise

ValueError: in user code:

<ipython-input-49-d1f74bd6a9c5>:3 detect_fn  *
    image, shapes = detection_model.preprocess(image)
c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\object_detection\meta_architectures\ssd_meta_arch.py:484 preprocess  *
    normalized_inputs, self._image_resizer_fn)
c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\object_detection\utils\shape_utils.py:492 resize_images_and_return_shapes  *
    outputs = static_or_dynamic_map_fn(
c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\object_detection\utils\shape_utils.py:246 static_or_dynamic_map_fn  *
    outputs = [fn(arg) for arg in tf.unstack(elems)]
c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\object_detection\core\preprocessor.py:3214 resize_image  *
    new_image = tf.image.resize_images(
c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\util\dispatch.py:201 wrapper  **
    return target(*args, **kwargs)
c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\ops\image_ops_impl.py:1367 resize_images
    skip_resize_if_same=True)
c:\users\admin\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\ops\image_ops_impl.py:1219 _resize_images_common
    raise ValueError('\'images\' must have either 3 or 4 dimensions.')

ValueError: 'images' must have either 3 or 4 dimensions.

can anyone help?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.