70 lines
2.4 KiB
Python
70 lines
2.4 KiB
Python
import cv2
|
|
import mediapipe as mp
|
|
import json
|
|
import time
|
|
|
|
# Inicializa o vídeo a partir da webcam (ou outro dispositivo de captura)
|
|
cap = cv2.VideoCapture(0)
|
|
|
|
# Variáveis para controle de tempo
|
|
file_path = 'face.json' # Caminho do arquivo para salvar as coordenadas
|
|
max_readings = 10 # Número máximo de leituras a serem mantidas
|
|
|
|
# Inicializa o módulo MediaPipe Face Detection
|
|
mp_face_detection = mp.solutions.face_detection
|
|
face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.5)
|
|
|
|
# Lista para armazenar as leituras
|
|
readings = []
|
|
|
|
while True:
|
|
# Captura o frame da câmera
|
|
ret, frame = cap.read()
|
|
|
|
# Conversão para escala de cinza para facilitar a detecção
|
|
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
|
|
|
# Realiza a detecção de rostos no frame
|
|
results = face_detection.process(frame_rgb)
|
|
|
|
current_readings = []
|
|
|
|
# Verifica se há rostos detectados
|
|
if results.detections:
|
|
for idx, detection in enumerate(results.detections):
|
|
bboxC = detection.location_data.relative_bounding_box
|
|
ih, iw, _ = frame.shape
|
|
x, y, w, h = int(bboxC.xmin * iw), int(bboxC.ymin * ih), int(bboxC.width * iw), int(bboxC.height * ih)
|
|
|
|
# Adiciona as informações do rosto à lista de leituras
|
|
current_readings.append({'id': idx, 'x': x, 'y': y, 'largura': w, 'altura': h})
|
|
|
|
# Desenha o retângulo ao redor do rosto detectado
|
|
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
|
|
|
|
# Escreve o número do rosto sobre o retângulo
|
|
cv2.putText(frame, f'Rosto {idx}', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
|
|
|
|
timestamp = time.time() # Captura o timestamp atual
|
|
readings.append({'timestamp': timestamp, 'rostos': current_readings})
|
|
|
|
# Se a lista atingir o limite máximo, remover a leitura mais antiga
|
|
if len(readings) > max_readings:
|
|
readings.pop(0)
|
|
|
|
# Salvar as coordenadas no arquivo a cada intervalo de tempo
|
|
if len(readings) == max_readings:
|
|
with open(file_path, 'w') as file:
|
|
json.dump({'frames': readings}, file)
|
|
|
|
# Mostra o frame com os retângulos e números identificadores
|
|
cv2.imshow('Detecção de Objetos', frame)
|
|
|
|
# Verifica se o usuário pressionou a tecla 'q' para sair do loop
|
|
if cv2.waitKey(1) & 0xFF == ord('q'):
|
|
break
|
|
|
|
# Libera a captura de vídeo e fecha as janelas
|
|
cap.release()
|
|
cv2.destroyAllWindows()
|