-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
48 lines (35 loc) · 1.1 KB
/
main.py
File metadata and controls
48 lines (35 loc) · 1.1 KB
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
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from PIL import Image
try:
img = Image.open('bibble.jpg')
img = np.array(img)
except FileNotFoundError:
print("Erro: Arquivo de imagem não encontrado")
if 'img' not in locals():
print("Usando uma matriz de imagem simulada")
img = np.random.randint(0, 256, size=(100, 150, 3), dtype=np.uint8)
h, w, d = img.shape
data = img[:, :, :3].reshape(h * w, 3).astype(float)
K = 10
print(f"Executando K-Means com K = {K}...")
kmeans = KMeans(n_clusters=K, n_init='auto', random_state=42)
kmeans.fit(data)
cores_quantizadas = kmeans.cluster_centers_.astype(np.uint8)
labels = kmeans.labels_
img_quantizada = np.zeros_like(data, dtype=np.uint8)
for i in range(h * w):
img_quantizada[i] = cores_quantizadas[labels[i]]
img_quantizada = img_quantizada.reshape(h, w, 3)
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Imagem Original')
plt.imshow(img)
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title(f'K-Means: {K} Cores')
plt.imshow(img_quantizada)
plt.axis('off')
plt.tight_layout()
plt.show()