File size: 4,876 Bytes
a146cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import clip
from PIL import Image
import numpy as np
import cv2
from typing import Dict, List, Tuple
import json

class ImageProcessor:
    def __init__(self):
        """Inicializa o processador com modelo CLIP"""
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.model, self.preprocess = clip.load("ViT-B/32", device=self.device)
        print(f"🤖 Modelo CLIP carregado no dispositivo: {self.device}")
    
    def generate_embedding(self, image_path: str) -> np.ndarray:
        """Gera embedding da imagem usando CLIP"""
        try:
            image = Image.open(image_path).convert('RGB')
            image_input = self.preprocess(image).unsqueeze(0).to(self.device)
            
            with torch.no_grad():
                image_features = self.model.encode_image(image_input)
                # Normaliza o vetor
                image_features = image_features / image_features.norm(dim=-1, keepdim=True)
                
            return image_features.cpu().numpy().flatten()
        except Exception as e:
            print(f"❌ Erro ao gerar embedding para {image_path}: {e}")
            return None
    
    def analyze_image_technical(self, image_path: str) -> Dict:
        """Realiza análise técnica da imagem"""
        try:
            # Carrega imagem
            image = cv2.imread(image_path)
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            
            # Análise de cores dominantes
            dominant_colors = self._get_dominant_colors(image_rgb)
            
            # Análise de brilho e contraste
            brightness = np.mean(image_rgb)
            contrast = np.std(image_rgb)
            
            # Detecção de bordas (complexidade visual)
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            edges = cv2.Canny(gray, 50, 150)
            edge_density = np.sum(edges > 0) / (edges.shape[0] * edges.shape[1])
            
            # Análise de saturação
            hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
            saturation = np.mean(hsv[:, :, 1])
            
            return {
                "dominant_colors": dominant_colors,
                "brightness": float(brightness),
                "contrast": float(contrast),
                "edge_density": float(edge_density),
                "saturation": float(saturation),
                "image_size": {
                    "width": image.shape[1],
                    "height": image.shape[0]
                }
            }
        except Exception as e:
            print(f"❌ Erro na análise técnica de {image_path}: {e}")
            return {}
    
    def _get_dominant_colors(self, image: np.ndarray, k: int = 5) -> List[Dict]:
        """Extrai cores dominantes usando K-means"""
        try:
            # Reshape da imagem para lista de pixels
            pixels = image.reshape(-1, 3)
            
            # K-means clustering
            from sklearn.cluster import KMeans
            kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
            kmeans.fit(pixels)
            
            # Calcula percentual de cada cor
            labels = kmeans.labels_
            unique, counts = np.unique(labels, return_counts=True)
            
            colors = []
            for i, color in enumerate(kmeans.cluster_centers_):
                percentage = counts[i] / len(labels) * 100
                colors.append({
                    "rgb": [int(c) for c in color],
                    "hex": "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2])),
                    "percentage": float(percentage)
                })
            
            # Ordena por percentual
            colors.sort(key=lambda x: x['percentage'], reverse=True)
            return colors
        except Exception as e:
            print(f"❌ Erro ao extrair cores dominantes: {e}")
            return []
    
    def create_thumbnail(self, image_path: str, output_path: str, size: Tuple[int, int] = (200, 200)) -> bool:
        """Cria thumbnail da imagem"""
        try:
            with Image.open(image_path) as img:
                # Mantém proporção
                img.thumbnail(size, Image.Resampling.LANCZOS)
                
                # Cria imagem quadrada com fundo branco
                thumbnail = Image.new('RGB', size, (255, 255, 255))
                
                # Centraliza a imagem
                x = (size[0] - img.width) // 2
                y = (size[1] - img.height) // 2
                thumbnail.paste(img, (x, y))
                
                # Salva thumbnail
                thumbnail.save(output_path, 'PNG', quality=95)
                return True
        except Exception as e:
            print(f"❌ Erro ao criar thumbnail de {image_path}: {e}")
            return False