Skip to content

Instantly share code, notes, and snippets.

@gbaeza2002
Created September 20, 2025 02:45
Show Gist options
  • Select an option

  • Save gbaeza2002/0b7b53190468df8038ae049949f999c1 to your computer and use it in GitHub Desktop.

Select an option

Save gbaeza2002/0b7b53190468df8038ae049949f999c1 to your computer and use it in GitHub Desktop.
Script para deteccion de gatos
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions
# -----------------------------
# CONFIGURACIONES
# -----------------------------
DATASET_DIR = "./imagenes caso D" # Carpeta de imágenes
TARGET_CLASSES = ["cat", "tiger", "panther"] # Palabras clave de las clases
IMG_SIZE = (224, 224)
# -----------------------------
# CARGAR MODELO PREENTRENADO
# -----------------------------
model = MobileNetV2(weights="imagenet")
# -----------------------------
# VARIABLES PARA RECUENTO
# -----------------------------
counts = {cls: 0 for cls in TARGET_CLASSES}
# -----------------------------
# PROCESAR IMÁGENES
# -----------------------------
for img_name in os.listdir(DATASET_DIR):
img_path = os.path.join(DATASET_DIR, img_name)
try:
# Cargar y preprocesar imagen
img = image.load_img(img_path, target_size=IMG_SIZE)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
# Predicción
preds = model.predict(x)
decoded = decode_predictions(preds, top=3)[0]
# Buscar si la predicción corresponde a nuestras clases objetivo
found_class = None
for _, label, prob in decoded:
label = label.lower()
if "cat" in label and "wildcat" not in label: # excluir wildcat
found_class = "cat"
break
elif "tiger" in label:
found_class = "tiger"
break
elif "panther" in label or "jaguar" in label or "leopard" in label:
found_class = "panther"
break
if found_class:
counts[found_class] += 1
print(f"{img_name} -> {found_class}")
else:
print(f"{img_name} -> No identificado en {TARGET_CLASSES}")
except Exception as e:
print(f"Error con {img_name}: {e}")
# -----------------------------
# MOSTRAR RECUENTO FINAL
# -----------------------------
print("\nRecuento final:")
for animal, count in counts.items():
print(f"{animal}: {count}")
# -----------------------------
# GRAFICAR
# -----------------------------
plt.bar(counts.keys(), counts.values())
plt.title("Recuento de animales detectados")
plt.xlabel("Animal")
plt.ylabel("Cantidad")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment