【问题标题】:NameError: name 'category_index' is not defined, how to fix?NameError:名称'category_index'未定义,如何解决?
【发布时间】:2022-06-18 04:32:38
【问题描述】:

我尝试运行一个实时对象检测程序,但它给了我这个错误。

NameError: name 'category_index' 未定义

cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

while cap.isOpened(): 
    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=.8,
                agnostic_mode=False)

    cv2.imshow('object detection',  cv2.resize(image_np_with_detections, (800, 600)))
    
    if cv2.waitKey(10) & 0xFF == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break

有谁知道如何解决这个问题?

【问题讨论】:

  • 能否请您发布您的代码而不是错误的屏幕截图?
  • 抱歉刚刚发布

标签: python tensorflow object-detection object-detection-api


【解决方案1】:

您在viz_utils.visualize_boxes_and_labels_on_image_array 函数调用中传递了一个未声明的变量category_index

Python 的 NameError 是在找不到本地或全局名称时引发的 exception。 您需要确保在使用之前声明任何变量。

【讨论】:

    【解决方案2】:

    我发现解决办法是在代码之前运行这个

    category_index = label_map_util.create_category_index_from_labelmap(files['LABELMAP'])

    【讨论】:

      【解决方案3】:

      您可以将此行添加为占位符以绕过错误

      category_index ={'name':'dummyname','id':1}

      【讨论】:

        猜你喜欢
        • 2018-07-14
        • 1970-01-01
        • 2021-09-22
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        • 2021-04-15
        • 2019-01-26
        相关资源
        最近更新 更多