Spaces:
Sleeping
Sleeping
Use MiniBatchKmeans for faster compression using random pixel sample for centroid fitting
Browse files
app.py
CHANGED
|
@@ -1,19 +1,36 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
-
from sklearn.cluster import
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
import os
|
| 6 |
import tempfile
|
| 7 |
from io import BytesIO
|
| 8 |
|
| 9 |
-
def
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
labels = model.predict(pixels)
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
|
| 18 |
def process(filepath, k):
|
| 19 |
if filepath is None:
|
|
@@ -23,7 +40,7 @@ def process(filepath, k):
|
|
| 23 |
orig = np.array(Image.open(filepath).convert('RGB'))
|
| 24 |
|
| 25 |
# Compress
|
| 26 |
-
comp =
|
| 27 |
|
| 28 |
def get_size(img):
|
| 29 |
with BytesIO() as buf:
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
+
from sklearn.cluster import MiniBatchKMeans
|
| 4 |
+
from sklearn.utils import shuffle
|
| 5 |
from PIL import Image
|
| 6 |
import os
|
| 7 |
import tempfile
|
| 8 |
from io import BytesIO
|
| 9 |
|
| 10 |
+
def compress_kmeans(image: np.ndarray, k: int, random_state: 42) -> np.ndarray:
|
| 11 |
+
"""
|
| 12 |
+
Faster K‑Means compression using a random pixel sample for centroid fitting.
|
| 13 |
+
"""
|
| 14 |
+
pixels = image.reshape(-1, 3).astype(np.float32)
|
| 15 |
+
|
| 16 |
+
sample_size = min(20000, len(pixels))
|
| 17 |
+
sample = shuffle(pixels, random_state=random_state)[:sample_size]
|
| 18 |
+
|
| 19 |
+
model = MiniBatchKMeans(
|
| 20 |
+
n_clusters=k,
|
| 21 |
+
batch_size=min(1024, sample_size),
|
| 22 |
+
n_init='auto',
|
| 23 |
+
max_iter=50,
|
| 24 |
+
random_state=random_state,
|
| 25 |
+
verbose=0,
|
| 26 |
+
)
|
| 27 |
+
model.fit(sample)
|
| 28 |
+
|
| 29 |
labels = model.predict(pixels)
|
| 30 |
+
centres = model.cluster_centers_.astype(np.uint8)
|
| 31 |
+
compressed_pixels = centres[labels]
|
| 32 |
+
|
| 33 |
+
return compressed_pixels.reshape(image.shape)
|
| 34 |
|
| 35 |
def process(filepath, k):
|
| 36 |
if filepath is None:
|
|
|
|
| 40 |
orig = np.array(Image.open(filepath).convert('RGB'))
|
| 41 |
|
| 42 |
# Compress
|
| 43 |
+
comp = compress_kmeans(orig, k, random_state=42)
|
| 44 |
|
| 45 |
def get_size(img):
|
| 46 |
with BytesIO() as buf:
|