TensorFlow / Python: Detección de Objetos con Modelos Pre-Entrenados de Object Detection API

El Desarrollo de una Aplicación de Detección de Objetos con “TensorFlow”, contempla la creación de una aplicación que pueda detectar y reconocer objetos en imágenes o videos utilizando la API de Detección de Objetos de TensorFlow. Esto implica el uso de modelos de aprendizaje profundo pre-entrenados para identificar objetos en tiempo real o en imágenes estáticas.

Este código demuestra cómo usar una red neuronal pre-entrenada en TensorFlow para realizar detección de objetos en imágenes. La detección de objetos es una tarea crucial en la visión por computadora y tiene muchas aplicaciones, como la detección de objetos en imágenes médicas, vehículos autónomos, seguridad y más.

Instalaremos la versión necesarias de TensorFlow y TensorFlow Slim, que son requeridas para ejecutar el código de ejemplo:

!pip install -U --pre tensorflow=="2.*"
!pip install tf_slim

Asegurarnos de que el entorno de ejecución tenga acceso al repositorio de modelos de TensorFlow antes de intentar cargar un modelo pre-entrenado. Si el repositorio no está presente localmente, lo clona desde GitHub.

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():
  !git clone --depth 1 https://github.com/tensorflow/models
%%bash
cd models/research/
protoc object_detection/protos/*.proto --python_out=.
cp object_detection/packages/tf2/setup.py .
python -m pip install .
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import pathlib
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from IPython.display import display

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

if "models" in pathlib.Path.cwd().parts:
  while "models" in pathlib.Path.cwd().parts:
    os.chdir('..')

# Descargar e importar el modelo de detección de objetos
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))
  return model

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)

model_name = 'ssd_inception_v2_coco_2017_11_17'
detection_model = load_model(model_name)

# Convertir el modelo a una función que tome un tensor de imagen como entrada y devuelva resultados de detección
def run_inference_for_single_image(model, image):
  image = np.asarray(image)
  # El modelo espera un tensor con forma: [1, None, None, 3]
  input_tensor = tf.convert_to_tensor(image)
  input_tensor = input_tensor[tf.newaxis,...]

  # Realizar la detección
  model_fn = model.signatures['serving_default']
  output_dict = model_fn(input_tensor)

  # Las salidas de este modelo son arrays
  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

  # Detecciones de clases deben ser ints
  output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)
    
  # Si es necesario, se pueden añadir más clases o etiquetas al archivo pbtxt, luego se pueden visualizar aquí

  return output_dict

# Cargar una imagen para la detección
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")))

for image_path in TEST_IMAGE_PATHS:
  print('Detección en: {}'.format(image_path))
  image_np = np.array(Image.open(image_path))
  output_dict = run_inference_for_single_image(detection_model, image_np)
  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)
  display(Image.fromarray(image_np))

Estos son los pasos que sigue este código:

  1. Descargar e importar el modelo pre-entrenado: El código descarga un modelo de detección de objetos pre-entrenado llamado ssd_inception_v2_coco_2017_11_17. Estos modelos son entrenados en conjuntos de datos masivos y son capaces de detectar una amplia variedad de objetos en imágenes.
  2. Configurar el modelo para la detección: El modelo se carga en TensorFlow y se configura para realizar detecciones. Esto implica definir una función run_inference_for_single_image que toma una imagen de entrada y ejecuta la detección utilizando el modelo.
  3. Cargar imágenes de prueba: Se cargan imágenes de prueba ubicadas en el directorio models/research/object_detection/test_images. Estas imágenes se utilizarán para demostrar la detección de objetos.
  4. Realizar detección de objetos: Para cada imagen de prueba, el código llama a la función run_inference_for_single_image para realizar la detección de objetos. El modelo detecta objetos en la imagen y devuelve información sobre las ubicaciones, clases y puntuaciones de confianza de los objetos detectados.
  5. Visualizar resultados: Los resultados de la detección se visualizan en la imagen original. El código agrega cajas de delimitación alrededor de los objetos detectados y etiquetas que indican qué objetos se han detectado.

Detección en: models/research/object_detection/test_images/image1.jpg

Detección en: models/research/object_detection/test_images/image2.jpg

La importancia de este código radica en su capacidad para mostrar cómo se puede aprovechar un modelo de detección de objetos pre-entrenado en TensorFlow para realizar tareas de visión por computadora de manera efectiva y eficiente. Esto es fundamental para aplicaciones como la seguridad, la automatización industrial, la detección médica y muchas otras. El código proporciona una base para comprender y utilizar la detección de objetos en la práctica.

14 thoughts on “TensorFlow / Python: Detección de Objetos con Modelos Pre-Entrenados de Object Detection API

  1. What i do not understood is in truth how you are not actually a lot more smartlyliked than you may be now You are very intelligent You realize therefore significantly in the case of this topic produced me individually imagine it from numerous numerous angles Its like men and women dont seem to be fascinated until it is one thing to do with Woman gaga Your own stuffs nice All the time care for it up

  2. Attractive section of content I just stumbled upon your blog and in accession capital to assert that I get actually enjoyed account your blog posts Anyway I will be subscribing to your augment and even I achievement you access consistently fast

  3. I do agree with all the ideas you have introduced on your post They are very convincing and will definitely work Still the posts are very short for newbies May just you please prolong them a little from subsequent time Thank you for the post

  4. I loved as much as you will receive carried out right here The sketch is tasteful your authored subject matter stylish nonetheless you command get got an edginess over that you wish be delivering the following unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this hike

  5. Hi Neat post There is a problem along with your website in internet explorer would test this IE still is the market chief and a good section of other folks will pass over your magnificent writing due to this problem

  6. of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again

  7. Hello Neat post Theres an issue together with your site in internet explorer would check this IE still is the marketplace chief and a large element of other folks will leave out your magnificent writing due to this problem

  8. I do agree with all the ideas you have introduced on your post They are very convincing and will definitely work Still the posts are very short for newbies May just you please prolong them a little from subsequent time Thank you for the post

Deja un comentario