Spaces:
Sleeping
Sleeping
File size: 11,081 Bytes
d23e909 ab62897 be04296 d23e909 be04296 ab62897 d23e909 be04296 d23e909 be04296 ab62897 d23e909 be04296 d23e909 be04296 d23e909 be04296 d23e909 be04296 d23e909 be04296 d23e909 be04296 d23e909 be04296 d23e909 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
"""
Simplified face labeling module.
Provides a streamlined UI for face detection and labeling with minimal complexity.
"""
import streamlit as st
import numpy as np
import cv2
import logging
import time
from typing import List, Dict, Tuple, Any, Set
# Configurar logging
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
def draw_numbered_faces(image: np.ndarray, faces: List[Tuple[int, int, int, int]],
max_faces: int = 5) -> np.ndarray:
"""
Draw numbered rectangles on detected faces.
Args:
image: Image in numpy array format (RGB)
faces: List of tuples (x, y, w, h) with face coordinates
max_faces: Maximum number of faces to display
Returns:
Image with labeled faces
"""
# Work with a copy to avoid modifying the original
labeled_img = image.copy()
# Limit to max_faces faces
faces_to_draw = faces[:max_faces] if len(faces) > max_faces else faces
# Get removed faces set (if exists)
removed_faces = st.session_state.get("removed_faces", set())
# Draw each face
for i, (x, y, w, h) in enumerate(faces_to_draw):
face_key = f"face_{i}"
# Skip if this face was marked as removed
if face_key in removed_faces:
continue
# Draw green rectangle
cv2.rectangle(labeled_img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Add numbered label
label = f"Face {i+1}"
cv2.putText(labeled_img, label, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
return labeled_img
def extract_face_thumbnails(image: np.ndarray, faces: List[Tuple[int, int, int, int]],
max_faces: int = 5) -> Dict[int, np.ndarray]:
"""
Extracts thumbnails of detected faces.
Args:
image: Image in numpy array format (RGB)
faces: List of tuples (x, y, w, h) with face coordinates
max_faces: Maximum number of faces to process
Returns:
Dictionary with face index and its cropped image
"""
thumbnails = {}
# Limit to max_faces faces
faces_to_extract = faces[:max_faces] if len(faces) > max_faces else faces
# Extract each thumbnail
for i, (x, y, w, h) in enumerate(faces_to_extract):
# Apply a small margin around the face if possible
margin = int(min(w, h) * 0.1) # 10% margin
# Ensure we don't go out of the image bounds
img_h, img_w = image.shape[:2]
x_start = max(0, x - margin)
y_start = max(0, y - margin)
x_end = min(img_w, x + w + margin)
y_end = min(img_h, y + h + margin)
# Extract the thumbnail with margin
face_thumbnail = image[y_start:y_end, x_start:x_end]
thumbnails[i] = face_thumbnail
return thumbnails
def simple_face_labeling_ui(image: np.ndarray, faces: List[Tuple[int, int, int, int]],
max_faces: int = 5) -> Dict[str, Any]:
"""
Displays a simplified interface for labeling faces.
Args:
image: Image in numpy array format (RGB)
faces: List of tuples (x, y, w, h) with face coordinates
max_faces: Maximum number of faces to process
Returns:
Dictionary with information about labeled faces
"""
# Iniciar timestamp de sesi贸n si no existe (para crear claves 煤nicas)
if "session_timestamp" not in st.session_state:
st.session_state.session_timestamp = int(time.time())
# Initialize session state for face labels and removed faces
if "face_labels" not in st.session_state:
st.session_state.face_labels = {}
if "removed_faces" not in st.session_state:
st.session_state.removed_faces = set()
# Timestamp para generar IDs 煤nicos para los botones en esta sesi贸n
timestamp = st.session_state.session_timestamp
# Limit to max_faces faces
faces_to_show = faces[:max_faces] if len(faces) > max_faces else faces
num_faces = len(faces_to_show)
# Display labeled image
labeled_image = draw_numbered_faces(image, faces_to_show)
st.image(labeled_image, caption="Detected Faces", use_column_width=True)
# Only proceed if faces were detected
if num_faces > 0:
st.success(f"{num_faces} face(s) detected in the image")
# Extract thumbnails
thumbnails = extract_face_thumbnails(image, faces_to_show)
# Create a form for labeling
st.subheader("Enter names for detected faces")
# Lista para seguir qu茅 caras se muestran (para preparar el resultado)
displayed_faces = []
# Create a simple list of faces with names and remove buttons
for i, (x, y, w, h) in enumerate(faces_to_show):
face_key = f"face_{i}"
# Skip if this face was marked as removed
if face_key in st.session_state.removed_faces:
continue
displayed_faces.append((i, face_key, (x, y, w, h)))
# Create a row with thumbnail, name field and remove button
cols = st.columns([1, 3, 1])
with cols[0]:
# Display thumbnail
if i in thumbnails:
st.image(thumbnails[i], caption=f"Face {i+1}", width=80)
with cols[1]:
# Input field for name
label = st.text_input(
f"Name for Face {i+1}:",
key=f"label_{face_key}_{timestamp}",
value=st.session_state.face_labels.get(face_key, "")
)
# Save to session state
st.session_state.face_labels[face_key] = label
with cols[2]:
# Cada bot贸n tiene una clave 煤nica para esta sesi贸n
remove_button_key = f"btn_remove_{face_key}_{timestamp}"
if st.button("Remove", key=remove_button_key):
# Marcar la cara como eliminada
st.session_state.removed_faces.add(face_key)
# Eliminar la etiqueta si existe
if face_key in st.session_state.face_labels:
del st.session_state.face_labels[face_key]
# Forzar rerun para actualizar la interfaz
st.experimental_rerun()
# Prepare result data
result = {
"success": True,
"num_faces": num_faces,
"labeled_image": labeled_image
}
# Add face data
labeled_faces = {}
# Usar solo las caras que se mostraron
for i, face_key, coords in displayed_faces:
# Check if this face has a label
label = st.session_state.face_labels.get(face_key, "")
if label:
labeled_faces[face_key] = {
"index": i,
"label": label,
"coordinates": coords
}
# Add to result
result["labeled_faces"] = labeled_faces
result["can_proceed"] = len(labeled_faces) > 0
# Show proceed button if at least one face is labeled
if result["can_proceed"]:
if st.button("Continue to Analysis", key=f"continue_to_analysis_{timestamp}"):
result["proceed_to_analysis"] = True
else:
result["proceed_to_analysis"] = False
else:
st.warning("Please provide at least one name to continue to analysis.")
result["proceed_to_analysis"] = False
return result
else:
st.warning("No faces detected in the image.")
return {
"success": False,
"num_faces": 0,
"message": "No faces detected in the image."
}
def simple_face_detection_and_labeling_ui(image: np.ndarray, face_service: Any) -> Dict[str, Any]:
"""
Main function for simplified face detection and labeling.
Args:
image: Image in numpy array format (RGB)
face_service: Face detection service
Returns:
Dictionary with processed results
"""
# Ensure we have an image
if image is None:
st.warning("No image available for processing.")
return {
"success": False,
"message": "No image available for processing."
}
# Set maximum faces
max_faces = 5
# Convert to BGR for detection if needed
img_bgr = None
if len(image.shape) == 3 and image.shape[2] == 3:
img_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
else:
img_bgr = image.copy()
# Perform face detection
with st.spinner("Detecting faces..."):
faces = face_service.detect_faces(img_bgr)
# Check if any faces were detected
if faces is None or len(faces) == 0:
st.warning("No faces detected in the image.")
st.image(image, caption="Uploaded image (no faces detected)", use_column_width=True)
return {
"success": False,
"message": "No faces detected in the image."
}
# Save detected faces in session state
st.session_state["detected_faces"] = faces
# Show the simple labeling UI
labeling_result = simple_face_labeling_ui(image, faces, max_faces)
# Handle result
if labeling_result.get("proceed_to_analysis", False):
# Prepare data for analysis
faces_to_analyze = []
labeled_faces = labeling_result.get("labeled_faces", {})
# Process each labeled face
for face_key, face_info in labeled_faces.items():
index = face_info.get("index", 0)
label = face_info.get("label", "")
coords = face_info.get("coordinates", (0, 0, 0, 0))
# Extract thumbnail
x, y, w, h = coords
margin = int(min(w, h) * 0.1)
img_h, img_w = image.shape[:2]
x_start = max(0, x - margin)
y_start = max(0, y - margin)
x_end = min(img_w, x + w + margin)
y_end = min(img_h, y + h + margin)
thumbnail = image[y_start:y_end, x_start:x_end]
# Add to faces to analyze
faces_to_analyze.append({
"key": face_key,
"label": label,
"coordinates": coords,
"thumbnail": thumbnail
})
# Return analysis data
return {
"success": True,
"proceed_to_analysis": True,
"faces_to_analyze": faces_to_analyze
}
# Return result without proceeding
return {
"success": labeling_result.get("success", False),
"proceed_to_analysis": False,
"message": labeling_result.get("message", "")
}
|