I got an error ,IndexError: list index out of range.
it worked on a other machine but after i transferred it to a other machine it doesn’t work anymore.
Python: 3.8.5
tensorflow: 2.3.1
Traceback says:
JavaScript
x
11
11
1
tensorflow.python.autograph.impl.api.StagingError: in user code:
2
3
Load_Model.py:40 detect_fn *
4
image, shapes = detection_model.preprocess(image)
5
C:UsersTensorflowtensorflow 2.xmodelsresearchobject_detectionmeta_architecturesssd_meta_arch.py:482 preprocess *
6
normalized_inputs = self._feature_extractor.preprocess(inputs)
7
C:UsersTensorflowtensorflow 2.xmodelsresearchobject_detectionmodelsssd_resnet_v1_fpn_keras_feature_extractor.py:204 preprocess *
8
if resized_inputs.shape.as_list()[3] == 3:
9
10
IndexError: list index out of range
11
My code:
JavaScript
1
92
92
1
import tensorflow as tf
2
import os
3
import cv2
4
from object_detection.utils import label_map_util
5
from object_detection.utils import config_util
6
from object_detection.utils import visualization_utils as viz_utils
7
from object_detection.builders import model_builder
8
9
model_name = 'ssd_resnet101_v1_fpn_640x640_coco17_tpu-8'
10
data_dir = os.path.join(os.getcwd(), 'data')
11
models_dir = os.path.join(data_dir, 'models')
12
path_to_ckg = os.path.join(models_dir, os.path.join(model_name, 'pipeline.config'))
13
PATH_TO_CFG = os.path.join(models_dir)
14
path_to_cktp = os.path.join(models_dir, os.path.join(model_name, 'checkpoint/'))
15
label_filename = 'mscoco_label_map.pbtxt'
16
path_to_labels = os.path.join(models_dir, os.path.join(model_name, label_filename))
17
18
19
tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2)
20
21
#Enable GPU dynamic memory allocation
22
gpus = tf.config.experimental.list_physical_devices('GPU')
23
for gpu in gpus:
24
tf.config.experimental.set_memory_growth(gpu, True)
25
26
#Load pipeline config and build a detection model'
27
configs = config_util.get_configs_from_pipeline_file(path_to_ckg)
28
model_config = configs['model']
29
detection_model = model_builder.build(model_config=model_config, is_training=False)
30
31
#Restore checkpoint
32
ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
33
ckpt.restore(os.path.join(path_to_cktp, 'ckpt-0')).expect_partial()
34
35
@tf.function
36
def detect_fn(image):
37
"""Detect objects in image."""
38
39
image, shapes = detection_model.preprocess(image)
40
prediction_dict = detection_model.predict(image, shapes)
41
detections = detection_model.postprocess(prediction_dict, shapes)
42
43
return detections, prediction_dict, tf.reshape(shapes, [-1])
44
45
category_index = label_map_util.create_category_index_from_labelmap(path_to_labels,
46
use_display_name=True)
47
48
cap = cv2.VideoCapture('rtsp://username:pass@192.168.1.103:8000/tcp/av0_1')
49
50
import numpy as np
51
52
while True:
53
#Read frame from camera
54
ret, image_np = cap.read()
55
56
#Expand dimensions since the model expects images to have shape: [1, None, None, 3]
57
image_np_expanded = np.expand_dims(image_np, axis=0)
58
59
#Things to try:
60
#Flip horizontally
61
#image_np = np.fliplr(image_np).copy()
62
63
#Convert image to grayscale
64
#image_np = np.tile(
65
#np.mean(image_np, 2, keepdims=True), (1, 1, 3)).astype(np.uint8)
66
67
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
68
detections, predictions_dict, shapes = detect_fn(input_tensor)
69
70
label_id_offset = 1
71
image_np_with_detections = image_np.copy()
72
73
viz_utils.visualize_boxes_and_labels_on_image_array(
74
image_np_with_detections,
75
detections['detection_boxes'][0].numpy(),
76
(detections['detection_classes'][0].numpy() + label_id_offset).astype(int),
77
detections['detection_scores'][0].numpy(),
78
category_index,
79
use_normalized_coordinates=True,
80
max_boxes_to_draw=200,
81
min_score_thresh=.30,
82
agnostic_mode=False)
83
84
#Display output
85
cv2.imshow('object detection', cv2.resize(image_np_with_detections, (800, 600)))
86
87
if cv2.waitKey(25) & 0xFF == ord('q'):
88
break
89
90
cap.release()
91
cv2.destroyAllWindows()
92
I really cannot understand why such an error happens.
What is wrong in my codes? How should I fix this?
Advertisement
Answer
Define the detect_fn inside the get_model_detection_function function , something like this :
JavaScript
1
17
17
1
def get_model_detection_function(model):
2
"""Get a tf.function for detection."""
3
4
@tf.function
5
def detect_fn(image):
6
"""Detect objects in image."""
7
8
image, shapes = model.preprocess(image)
9
prediction_dict = model.predict(image, shapes)
10
detections = model.postprocess(prediction_dict, shapes)
11
12
return detections, prediction_dict, tf.reshape(shapes, [-1])
13
14
return detect_fn
15
16
detect_fn = get_model_detection_function(detection_model)
17
See if this helps 😊