当前位置: 首页 > 知识库问答 >
问题:

Python OpenCV未显示对象检测tensorflow的结果

松建本
2023-03-14
#!/usr/bin/env python
# coding: utf-8

# # Object Detection API Demo


import os
import pathlib


if "models" in pathlib.Path.cwd().parts:
  while "models" in pathlib.Path.cwd().parts:
    os.chdir('..')
elif not pathlib.Path('models').exists():
  get_ipython().system('git clone --depth 1 https://github.com/tensorflow/models')


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

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


# Import the object detection module.

# In[5]:


from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util


# Get a reference to webcam 
video_capture = cv2.VideoCapture(0)
# Patches:

# In[6]:


# patch tf1 into `utils.ops`
utils_ops.tf = tf.compat.v1

# Patch the location of gfile
tf.gfile = tf.io.gfile


# # Model preparation 

# ## Variables
# 
# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing the path.
# 
# By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

# ## Loader

# In[7]:


def load_model(model_name):
  base_url = 'http://download.tensorflow.org/models/object_detection/'
  model_file = model_name + '.tar.gz'
  model_dir = tf.keras.utils.get_file(
    fname=model_name, 
    origin=base_url + model_file,
    untar=True)

  model_dir = pathlib.Path(model_dir)/"saved_model"

  model = tf.saved_model.load(str(model_dir))
  model = model.signatures['serving_default']

  return model


# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

# In[8]:


# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = 'models/research/object_detection/data/mscoco_label_map.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)


# For the sake of simplicity we will test on 2 images:

# In[9]:


# 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 = pathlib.Path('models/research/object_detection/test_images')
TEST_IMAGE_PATHS = sorted(list(PATH_TO_TEST_IMAGES_DIR.glob("*.jpg")))
TEST_IMAGE_PATHS


# # Detection

# Load an object detection model:

# In[10]:


model_name = 'ssd_mobilenet_v1_coco_2017_11_17'
detection_model = load_model(model_name)


# Check the model's input signature, it expects a batch of 3-color images of type uint8: 

# In[11]:


print(detection_model.inputs)


# And retuns several outputs:

# In[12]:


detection_model.output_dtypes


# In[13]:


print(detection_model.output_shapes)


# Add a wrapper function to call the model, and cleanup the outputs:

# In[14]:


def run_inference_for_single_image(model, image):
  image = np.asarray(image)
  # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
  input_tensor = tf.convert_to_tensor(image)
  # The model expects a batch of images, so add an axis with `tf.newaxis`.
  input_tensor = input_tensor[tf.newaxis,...]

  # Run inference
  output_dict = model(input_tensor)

  # All outputs are batches tensors.
  # Convert to numpy arrays, and take index [0] to remove the batch dimension.
  # We're only interested in the first num_detections.
  num_detections = int(output_dict.pop('num_detections'))
  output_dict = {key:value[0, :num_detections].numpy() 
                 for key,value in output_dict.items()}
  output_dict['num_detections'] = num_detections

  # detection_classes should be ints.
  output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)

  # Handle models with masks:
  if 'detection_masks' in output_dict:
    # Reframe the the bbox mask to the image size.
    detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
              output_dict['detection_masks'], output_dict['detection_boxes'],
               image.shape[0], image.shape[1])      
    detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,
                                       tf.uint8)
    output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()

  return output_dict


# Run it on each test image and show the results:

# In[15]:



# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.

# Grab a single frame of video
while True:
  ret, image_np = video_capture.read()
  # Actual detection.
  output_dict = run_inference_for_single_image(detection_model, image_np)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks_reframed', None),
      use_normalized_coordinates=True,
      line_thickness=8)

  cv2.imshow('Detected',image_np)
  if cv2.waitKey(25) & 0xFF == ord('q'):
      cv2.destroyAllWindows()
      break

我从网络摄像头中添加了目标检测代码,当我运行此代码时,它会显示检测2-5秒,然后在imshow窗口中显示未响应。

注:

>

  • 我用的是cv2。等待键(1),cv2。waitKey(0)也是,结果相同。

    我正在使用tensorflow gpu,它检测到我的gpu:1050ti。

    但是OpenCV使用CPU来显示图像。

    更新部分:

    while True:
      ret, image_np = video_capture.read()
      if ret == False:
        break
      # Actual detection.
      output_dict = run_inference_for_single_image(detection_model, image_np)
      # Visualization of the results of a detection.
      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          output_dict['detection_boxes'],
          output_dict['detection_classes'],
          output_dict['detection_scores'],
          category_index,
          instance_masks=output_dict.get('detection_masks_reframed', None),
          use_normalized_coordinates=True,
          line_thickness=8)
    
      cv2.imshow('Detected',image_np)
      if cv2.waitKey(0) & 0xFF == ord('q'):
          break
    
    cv2.destroyAllWindows()
    video_capture.release()
    

    [已解决]我刚刚创建了新的conda环境并安装了tensorflow版本TF v1。15.2并使用https://pythonprogramming.net/video-tensorflow-object-detection-api-tutorial/ 链接

    现在它正在工作,但代码包含一些不推荐使用的函数。

  • 共有1个答案

    乌修筠
    2023-03-14

    使用以下函数调用的返回值。

    ret, image_np = video_capture.read()
    if ret == False:
        break
    

    此外,将cv2.destroyAllWindows()移到而条件之外。

    while True:
        #your code here
    
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
    
    cv2.destroyAllWindows()
    
     类似资料:
    • 在运行Android TF Detect演示并使用我重新训练的3类ssd_mobilenet_v1_coco模型时,我的TF Detect演示崩溃,给出一个IndexOutOfBoundException 12-26 17:53:13.931 224 29-25212/org.tensorflow.demo E/AndroidRuntime:致命异常:推断进程:org.tensorflow.dem

    • 我已经根据提供的文档正确安装了Tensorflow对象检测API。然而,当我需要训练我的网络时,没有训练。研究/object\u检测目录中的py文件。我能做些什么来解决这个问题吗? 链接:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md

    • 当我试图在Github上使用自己的指南测试tenstorFlow目标检测API时发生了一个错误我在运行他们指南中提到的测试脚本时遇到了以下错误 python对象检测/构建器/模型构建器测试。py/home/appu/anaconda3/envs/ml/lib/python3。6/importlib/_引导。py:219:RuntimeWarning:compiletime模块“tensorflow

    • 问题内容: 检查JavaScript中的对象属性是否为最佳方法是什么? 问题答案: 检查属性值是否为特殊值的通常方法是: 要检查对象是否实际上没有这样的属性,并因此在尝试访问它时默认情况下将返回: 检查与标识符关联的值是否为特殊值, 或者 尚未声明该标识符。注意:此方法是引用 未声明的标识符(注意:与的值不同)的唯一方法,且不会出现早期错误: 在ECMAScript 5之前的JavaScript版

    • 问题内容: 我正在运行docker image tensorflow:1.1.0。我通过在本地克隆tensorflow对象检测api github并为我的docker连接到该文件夹​​添加了它。我正在尝试重新创建他们的宠物示例。 我相信我所有的代码和代码都在正确的地方。但是,当我尝试重新训练时,tensorflow在开始训练之前会自行杀死,但不会出现任何问题或错误。 我想我有东西出没了,但是没有任