models icon indicating copy to clipboard operation
models copied to clipboard

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

Open ammarahmedghani opened this issue 5 years ago • 6 comments

while testing my trained modal using opencv and tenserflow i run the following block of code 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, (800, 600)))

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

and I get the following error message with this warning message " :\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:5: DeprecationWarning: Both axis > a.ndim and axis < -a.ndim - 1 are deprecated and will raise an AxisError in the future. """

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

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py in call(self, *args, **kwds) 826 tracing_count = self.experimental_get_tracing_count() 827 with trace.Trace(self._name) as tm: --> 828 result = self._call(*args, **kwds) 829 compiler = "xla" if self._experimental_compile else "nonXla" 830 new_tracing_count = self.experimental_get_tracing_count()

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds) 860 # In this case we have not created variables on the first call. So we can 861 # run the first trace but we should fail if variables are created. --> 862 results = self._stateful_fn(*args, **kwds) 863 if self._created_variables: 864 raise ValueError("Creating variables on a non-first call to a function"

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\function.py in call(self, *args, **kwargs) 2939 with self._lock: 2940 (graph_function, -> 2941 filtered_flat_args) = self._maybe_define_function(args, kwargs) 2942 return graph_function._call_flat( 2943 filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\function.py in _maybe_define_function(self, args, kwargs) 3359 3360 self._function_cache.missed.add(call_context_key) -> 3361 graph_function = self._create_graph_function(args, kwargs) 3362 self._function_cache.primary[cache_key] = graph_function 3363

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) 3204 arg_names=arg_names, 3205 override_flat_arg_shapes=override_flat_arg_shapes, -> 3206 capture_by_value=self._capture_by_value), 3207 self._function_attributes, 3208 function_spec=self.function_spec,

~\AppData\Roaming\Python\Python37\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) 988 _, original_func = tf_decorator.unwrap(python_func) 989 --> 990 func_outputs = python_func(*func_args, **func_kwargs) 991 992 # invariant: func_outputs contains only Tensors, CompositeTensors,

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py in wrapped_fn(*args, **kwds) 632 xla_context.Exit() 633 else: --> 634 out = weak_wrapped_fn().wrapped(*args, **kwds) 635 return out 636

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\func_graph.py in wrapper(*args, **kwargs) 975 except Exception as e: # pylint:disable=broad-except 976 if hasattr(e, "ag_error_metadata"): --> 977 raise e.ag_error_metadata.to_exception(e) 978 else: 979 raise

ValueError: in user code:

<ipython-input-19-10d4dee4a4b6>:11 detect_fn  *
    image, shapes = detection_model.preprocess(image)
C:\Users\DELL\AppData\Roaming\Python\Python37\site-packages\object_detection\meta_architectures\ssd_meta_arch.py:484 preprocess  *
    normalized_inputs, self._image_resizer_fn)
C:\Users\DELL\AppData\Roaming\Python\Python37\site-packages\object_detection\utils\shape_utils.py:492 resize_images_and_return_shapes  *
    outputs = static_or_dynamic_map_fn(
C:\Users\DELL\AppData\Roaming\Python\Python37\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\DELL\AppData\Roaming\Python\Python37\site-packages\object_detection\core\preprocessor.py:3241 resize_image  *
    new_image = tf.image.resize_images(
C:\Users\DELL\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\util\dispatch.py:201 wrapper  **
    return target(*args, **kwargs)
C:\Users\DELL\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\image_ops_impl.py:1468 resize_images
    skip_resize_if_same=True)
C:\Users\DELL\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\image_ops_impl.py:1320 _resize_images_common
    raise ValueError('\'images\' must have either 3 or 4 dimensions.')

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

ammarahmedghani avatar Apr 30 '21 21:04 ammarahmedghani

Hi @ammarahmedghani I think the following tutorial might help you resolve your issue

Nkosana-263 avatar May 03 '21 16:05 Nkosana-263

To continue with what Nkosana-263 mentioned, as I had the same error happening (but I followed that tutorial for guidance), if you do change your code to resemble the tutorial example, don't write this line:

image_np_expanded = np.expand_dims(image_np, axis=0)

As that is not used anywhere in the example. Alternatively, you can keep it in and modify this line:

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

Replace np.expand_dims(image_np, 0) with image_np_expanded as you're already doing the same thing.

After I did that, the dimension error stopped showing up. Hopefully for good.

Rodeazzo avatar May 09 '21 14:05 Rodeazzo

Is this still an issue?

ymodak avatar Jun 04 '21 17:06 ymodak

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you.

google-ml-butler[bot] avatar Jun 11 '21 18:06 google-ml-butler[bot]

Closing as stale. Please reopen if you'd like to work on this further.

google-ml-butler[bot] avatar Jun 18 '21 18:06 google-ml-butler[bot]

Are you satisfied with the resolution of your issue? Yes No

google-ml-butler[bot] avatar Jun 18 '21 18:06 google-ml-butler[bot]