Imagine um sistema que vê e entende imagens como um humano!
Visão computacional permite que computadores interpretem, analisem e tomem decisões baseadas em informações visuais.
Nesta aula, você vai criar sistemas que reconhecem rostos, detectam objetos, analisam comportamentos e muito mais!
ROI: 40% redução em perdas
ROI: 95% precisão em qualidade
ROI: 60% menos acidentes
ROI: 85% precisão diagnóstica
import cv2
import numpy as np
from tensorflow.keras.applications import MobileNetV2, VGG16
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing.image import img_to_array
import face_recognition
import os
from datetime import datetime
import json
import pandas as pd
class IntelligentVisionSystem:
def __init__(self):
"""Sistema completo de visão computacional"""
print("👁️ Inicializando Sistema de Visão Inteligente...")
# Carregar modelos pré-treinados
print("🔄 Carregando modelos...")
self.object_model = MobileNetV2(weights='imagenet')
print("✅ Modelo de objetos carregado")
# Classificador de faces
self.face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
# YOLO para detecção de objetos (mais preciso)
self.load_yolo_model()
print("🎯 Sistema pronto para análise visual!")
def load_yolo_model(self):
"""Carrega modelo YOLO para detecção de objetos"""
try:
# Baixar YOLO se não existir
weights_path = "yolov3.weights"
config_path = "yolov3.cfg"
names_path = "coco.names"
if not os.path.exists(weights_path):
print("📥 YOLO não encontrado. Usando detecção básica.")
self.yolo_net = None
return
self.yolo_net = cv2.dnn.readNet(weights_path, config_path)
with open(names_path, 'r') as f:
self.yolo_classes = [line.strip() for line in f.readlines()]
print("✅ YOLO carregado com sucesso")
except Exception as e:
print(f"⚠️ Erro ao carregar YOLO: {e}")
self.yolo_net = None
def detect_and_recognize_faces(self, image_path):
"""Detecta e reconhece rostos na imagem"""
print(f"👤 Analisando rostos em: {image_path}")
# Carregar imagem
image = cv2.imread(image_path)
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Detectar rostos
face_locations = face_recognition.face_locations(rgb_image)
face_encodings = face_recognition.face_encodings(rgb_image, face_locations)
results = {
'total_faces': len(face_locations),
'faces': [],
'analysis_time': datetime.now().isoformat()
}
for i, (face_encoding, face_location) in enumerate(zip(face_encodings, face_locations)):
top, right, bottom, left = face_location
face_info = {
'face_id': f"face_{i+1}",
'location': {
'top': int(top),
'right': int(right),
'bottom': int(bottom),
'left': int(left)
},
'size': {
'width': int(right - left),
'height': int(bottom - top)
}
}
results['faces'].append(face_info)
print(f"✅ {len(face_locations)} rosto(s) detectado(s)")
return results, image
def classify_objects(self, image_path):
"""Classifica objetos na imagem"""
print(f"🔍 Classificando objetos em: {image_path}")
# Preprocessar imagem
image = cv2.imread(image_path)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
resized = cv2.resize(image_rgb, (224, 224))
# Preparar para o modelo
img_array = img_to_array(resized)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
# Fazer predição
predictions = self.object_model.predict(img_array)
decoded_predictions = decode_predictions(predictions, top=5)[0]
results = {
'top_predictions': [],
'analysis_time': datetime.now().isoformat()
}
for i, (imagenet_id, label, score) in enumerate(decoded_predictions):
prediction = {
'rank': i + 1,
'object': label.replace('_', ' ').title(),
'confidence': float(score),
'percentage': f"{score * 100:.1f}%"
}
results['top_predictions'].append(prediction)
print(f"✅ Objeto principal: {decoded_predictions[0][1]} ({decoded_predictions[0][2]:.1%})")
return results
def detect_objects_yolo(self, image_path):
"""Detecta múltiplos objetos usando YOLO"""
if not self.yolo_net:
return {'error': 'YOLO não disponível'}
print(f"🎯 Detectando objetos com YOLO em: {image_path}")
image = cv2.imread(image_path)
height, width, channels = image.shape
# Preparar imagem para YOLO
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
self.yolo_net.setInput(blob)
outs = self.yolo_net.forward()
# Processar detecções
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# Aplicar Non-Maximum Suppression
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
detected_objects = []
if len(indexes) > 0:
for i in indexes.flatten():
x, y, w, h = boxes[i]
label = str(self.yolo_classes[class_ids[i]])
confidence = confidences[i]
detected_objects.append({
'object': label,
'confidence': confidence,
'bbox': {'x': x, 'y': y, 'width': w, 'height': h}
})
results = {
'total_objects': len(detected_objects),
'objects': detected_objects,
'analysis_time': datetime.now().isoformat()
}
print(f"✅ {len(detected_objects)} objeto(s) detectado(s)")
return results, image
def analyze_image_colors(self, image_path):
"""Analisa cores predominantes na imagem"""
print(f"🎨 Analisando cores em: {image_path}")
image = cv2.imread(image_path)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Redimensionar para acelerar processamento
small_image = cv2.resize(image_rgb, (150, 150))
# Converter para float e fazer clustering
data = small_image.reshape((-1, 3))
data = np.float32(data)
# K-means para encontrar cores predominantes
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
k = 5
_, labels, centers = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Calcular percentuais
unique, counts = np.unique(labels, return_counts=True)
total_pixels = len(labels)
color_analysis = []
for i, (center, count) in enumerate(zip(centers, counts)):
percentage = (count / total_pixels) * 100
color_rgb = tuple(map(int, center))
color_analysis.append({
'rank': i + 1,
'rgb': color_rgb,
'hex': '#{:02x}{:02x}{:02x}'.format(*color_rgb),
'percentage': round(percentage, 1)
})
# Ordenar por percentual
color_analysis.sort(key=lambda x: x['percentage'], reverse=True)
results = {
'dominant_colors': color_analysis,
'analysis_time': datetime.now().isoformat()
}
print(f"✅ Cor principal: {color_analysis[0]['hex']} ({color_analysis[0]['percentage']}%)")
return results
def comprehensive_analysis(self, image_path, output_dir="./vision_analysis"):
"""Análise completa da imagem"""
print(f"\n{'='*60}")
print(f"🔍 ANÁLISE COMPLETA: {os.path.basename(image_path)}")
print(f"{'='*60}")
os.makedirs(output_dir, exist_ok=True)
# Executar todas as análises
face_results, annotated_image = self.detect_and_recognize_faces(image_path)
object_results = self.classify_objects(image_path)
if self.yolo_net:
yolo_results, yolo_image = self.detect_objects_yolo(image_path)
else:
yolo_results = {'note': 'YOLO não disponível'}
yolo_image = None
color_results = self.analyze_image_colors(image_path)
# Compilar resultados
comprehensive_results = {
'file_info': {
'file_path': image_path,
'file_name': os.path.basename(image_path),
'analyzed_at': datetime.now().isoformat()
},
'face_detection': face_results,
'object_classification': object_results,
'object_detection': yolo_results,
'color_analysis': color_results
}
# Salvar resultados JSON
output_filename = f"{os.path.splitext(os.path.basename(image_path))[0]}_vision_analysis.json"
output_path = os.path.join(output_dir, output_filename)
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(comprehensive_results, f, indent=2, ensure_ascii=False)
# Gerar relatório visual
self.generate_visual_report(comprehensive_results, output_dir)
# Salvar imagens anotadas
if annotated_image is not None:
face_img_path = os.path.join(output_dir, f"{os.path.splitext(os.path.basename(image_path))[0]}_faces.jpg")
cv2.imwrite(face_img_path, annotated_image)
if yolo_image is not None:
yolo_img_path = os.path.join(output_dir, f"{os.path.splitext(os.path.basename(image_path))[0]}_objects.jpg")
cv2.imwrite(yolo_img_path, yolo_image)
print(f"💾 Análise salva em: {output_path}")
return comprehensive_results
def generate_visual_report(self, analysis, output_dir):
"""Gera relatório visual da análise"""
report_content = f"""
# 👁️ RELATÓRIO DE VISÃO COMPUTACIONAL
## 📁 Informações do Arquivo
- **Nome**: {analysis['file_info']['file_name']}
- **Analisado em**: {analysis['file_info']['analyzed_at']}
## 👤 Detecção Facial
- **Rostos encontrados**: {analysis['face_detection']['total_faces']}
"""
if analysis['face_detection']['faces']:
for face in analysis['face_detection']['faces']:
report_content += f"- **{face['face_id']}**: {face['size']['width']}x{face['size']['height']} pixels\n"
report_content += f"""
## 🔍 Classificação de Objetos
**Objeto principal**: {analysis['object_classification']['top_predictions'][0]['object']}
({analysis['object_classification']['top_predictions'][0]['percentage']})
### Top 5 Predições:
"""
for pred in analysis['object_classification']['top_predictions']:
report_content += f"{pred['rank']}. **{pred['object']}** - {pred['percentage']}\n"
if 'objects' in analysis['object_detection']:
report_content += f"\n## 🎯 Detecção de Múltiplos Objetos\n"
report_content += f"**Total detectado**: {analysis['object_detection']['total_objects']}\n\n"
for obj in analysis['object_detection']['objects']:
report_content += f"- **{obj['object']}**: {obj['confidence']:.1%}\n"
report_content += f"\n## 🎨 Análise de Cores\n"
for color in analysis['color_analysis']['dominant_colors']:
report_content += f"{color['rank']}. **{color['hex']}** - {color['percentage']}%\n"
# Salvar relatório
report_filename = f"{analysis['file_info']['file_name']}_vision_report.md"
report_path = os.path.join(output_dir, report_filename)
with open(report_path, 'w', encoding='utf-8') as f:
f.write(report_content)
print(f"📋 Relatório visual: {report_path}")
# Sistema de Monitoramento em Tempo Real
class RealTimeVisionSystem:
def __init__(self):
"""Sistema de monitoramento em tempo real"""
self.vision_system = IntelligentVisionSystem()
self.cap = None
def start_camera_monitoring(self, camera_id=0):
"""Inicia monitoramento por câmera"""
print("📹 Iniciando monitoramento em tempo real...")
self.cap = cv2.VideoCapture(camera_id)
if not self.cap.isOpened():
print("❌ Erro: Não foi possível abrir a câmera")
return
print("✅ Câmera iniciada. Pressione 'q' para sair")
while True:
ret, frame = self.cap.read()
if not ret:
break
# Detectar rostos em tempo real
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = self.vision_system.face_cascade.detectMultiScale(
gray, 1.1, 4, minSize=(30, 30)
)
# Desenhar retângulos nos rostos
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.putText(frame, f'Face {len(faces)}', (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# Mostrar informações na tela
cv2.putText(frame, f'Rostos: {len(faces)}', (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(frame, 'Pressione "q" para sair', (10, frame.shape[0] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
cv2.imshow('Monitoramento Inteligente', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
self.cap.release()
cv2.destroyAllWindows()
print("📹 Monitoramento encerrado")
# Exemplo de uso
if __name__ == "__main__":
print("👁️ INICIANDO SISTEMA DE VISÃO COMPUTACIONAL")
print("="*60)
# Sistema principal
vision_system = IntelligentVisionSystem()
# Exemplo de análise (substitua pelo caminho da sua imagem)
image_path = "exemplo_imagem.jpg"
if os.path.exists(image_path):
# Análise completa
results = vision_system.comprehensive_analysis(image_path)
print("\n🎯 RESUMO DA ANÁLISE:")
print(f"👤 Rostos: {results['face_detection']['total_faces']}")
if results['object_classification']['top_predictions']:
top_object = results['object_classification']['top_predictions'][0]
print(f"🔍 Objeto principal: {top_object['object']} ({top_object['percentage']})")
else:
print(f"⚠️ Imagem não encontrada: {image_path}")
print("📷 Teste com suas próprias imagens!")
# Para monitoramento em tempo real (descomente para usar):
# realtime_system = RealTimeVisionSystem()
# realtime_system.start_camera_monitoring()
print("\n🎉 Sistema de Visão Computacional pronto!")
Você acabou de criar um sistema profissional de reconhecimento de imagens que pode ser usado em inúmeras aplicações comerciais!
Na próxima aula, vamos aprender automação inteligente e criar sistemas que executam tarefas complexas de forma autônoma!
"Visão computacional é dar olhos à inteligência artificial"
- Isaque Victor