-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo_quantize_methods.py
580 lines (474 loc) · 20 KB
/
demo_quantize_methods.py
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
import timeit
from collections import Counter
from typing import Callable, Tuple, Optional, Union, List, Type
from PIL import Image
import cv2
import numpy as np
import scipy.cluster
from sklearn.cluster import KMeans, MeanShift, MiniBatchKMeans
import sklearn.utils
# import sklearn.metrics
from pyclustering.cluster import (
bsas,
mbsas,
dbscan,
optics,
syncnet,
syncsom,
ttsas,
xmeans,
center_initializer,
elbow,
kmeans,
kmedians,
)
from pyclustering.utils import type_metric, distance_metric
MAX_SIZE = 500
def test_pillow(
img_input: Image.Image, method: int
) -> Tuple[Type[Image.Image], List[List[int]]]:
img: Image.Image = img_input.copy()
img.thumbnail((MAX_SIZE, MAX_SIZE), Image.NEAREST)
threshold_pixel_percentage: float = 0.05
nb_colours: int = 20
nb_colours_under_threshold: int
nb_pixels: int = img.width * img.height
quantized_img: Image.Image
while True:
# method 0 = median cut 1 = maximum coverage 2 = fast octree
quantized_img = img.quantize(colors=nb_colours, method=method, kmeans=0)
nb_colours_under_threshold = 0
colours_list: [Tuple[int, int]] = quantized_img.getcolors(nb_colours)
for (count, pixel) in colours_list:
if count / nb_pixels < threshold_pixel_percentage:
nb_colours_under_threshold += 1
if nb_colours_under_threshold == 0:
break
nb_colours -= -(-nb_colours_under_threshold // 2) # ceil integer division
palette: [int] = quantized_img.getpalette()
colours_list: [[int]] = [palette[i : i + 3] for i in range(0, nb_colours * 3, 3)]
return quantized_img, colours_list
def test_pillow_median_cut(
img_input: Image.Image
) -> Tuple[Type[Image.Image], List[List[int]]]:
return test_pillow(img_input, 0)
def test_pillow_maximum_coverage(
img_input: Image.Image
) -> Tuple[Type[Image.Image], List[List[int]]]:
return test_pillow(img_input, 1)
def test_pillow_fast_octree(
img_input: Image.Image
) -> Tuple[Type[Image.Image], List[List[int]]]:
return test_pillow(img_input, 2)
def get_img_data(
img_input: Image.Image,
mini: bool = False,
conversion_method: int = cv2.COLOR_RGB2BGR,
) -> Tuple[np.ndarray, int, np.ndarray]:
img: np.ndarray = cv2.cvtColor(np.array(img_input), conversion_method)
ratio: float = min(
MAX_SIZE / img.shape[0], MAX_SIZE / img.shape[1]
) # calculate ratio
if mini:
ratio /= 6
img = cv2.resize(img, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_AREA)
nb_pixels: int = img.size
flat_img: np.ndarray = img.reshape((-1, 3))
flat_img: np.ndarray = np.float32(flat_img)
return img, nb_pixels, flat_img
def process_result(
center: np.ndarray,
label: np.ndarray,
shape: Tuple[int, int, int],
conversion_method: int = cv2.COLOR_BGR2RGB,
) -> Tuple[Type[Image.Image], np.ndarray]:
center: np.ndarray = np.uint8(center)
quantized_img: np.ndarray = center[label]
quantized_img = quantized_img.reshape(shape)
quantized_img = cv2.cvtColor(quantized_img, conversion_method)
center = cv2.cvtColor(np.expand_dims(center, axis=0), conversion_method)[0]
return Image.fromarray(quantized_img), center
def update_nb_colours(
label: np.ndarray,
nb_pixels: int,
threshold_pixel_percentage: float,
nb_colours: int, # , flat_img: np.ndarray
) -> Tuple[int, int]:
nb_colours_under_threshold: int = 0
label = label.flatten()
colour_count: Counter[int] = Counter(label)
for (pixel, count) in colour_count.items():
if count / nb_pixels < threshold_pixel_percentage:
nb_colours_under_threshold += 1
# silhouette = sklearn.metrics.silhouette_score(flat_img, label, metric='euclidean', sample_size=1000)
# print(f'nb_colours = {nb_colours}, silhouette_score = {silhouette}')
nb_colours -= -(-nb_colours_under_threshold // 2) # ceil integer division
return nb_colours, nb_colours_under_threshold
def test_opencv(
img_input: Image.Image, method1: int, method2: int
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input, False, method1)
threshold_pixel_percentage: float = 0.01
nb_colours: int = 20
nb_colours_under_threshold: int = nb_colours
criteria: Tuple[int, int, float] = (
cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,
10,
1.0,
)
center: Optional[np.ndarray] = None
label: Optional[np.ndarray] = None
while nb_colours_under_threshold > 0:
ret: float
ret, label, center = cv2.kmeans(
flat_img, nb_colours, None, criteria, 10, cv2.KMEANS_PP_CENTERS
)
nb_colours, nb_colours_under_threshold = update_nb_colours(
label, nb_pixels, threshold_pixel_percentage, nb_colours # , flat_img
)
return process_result(center, label, img.shape, method2)
def test_opencv_rgb(img_input: Image.Image) -> Tuple[Type[Image.Image], np.ndarray]:
return test_opencv(img_input, cv2.COLOR_RGB2BGR, cv2.COLOR_BGR2RGB)
def test_opencv_hsv(img_input: Image.Image) -> Tuple[Type[Image.Image], np.ndarray]:
return test_opencv(img_input, cv2.COLOR_RGB2HSV, cv2.COLOR_HSV2RGB)
def test_opencv_lab(img_input: Image.Image) -> Tuple[Type[Image.Image], np.ndarray]:
return test_opencv(img_input, cv2.COLOR_RGB2Lab, cv2.COLOR_Lab2RGB)
def test_scipy(img_input: Image.Image) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
# minimum percentage of image coverage each colour needs to be, lower for more colours
threshold_pixel_percentage: float = 0.02
nb_colours: int = 20
nb_colours_under_threshold: int = nb_colours
centroids: Optional[np.ndarray] = None
qnt: Optional[np.ndarray] = None
while nb_colours_under_threshold > 0:
# performing the clustering
centroids, _ = scipy.cluster.vq.kmeans(flat_img, nb_colours)
# quantization
qnt, _ = scipy.cluster.vq.vq(flat_img, centroids)
nb_colours, nb_colours_under_threshold = update_nb_colours(
qnt, nb_pixels, threshold_pixel_percentage, nb_colours # , flat_img
)
# reshaping the result of the quantization
centers_idx: np.ndarray = np.reshape(qnt, (img.shape[0], img.shape[1]))
return process_result(centroids, centers_idx, img.shape)
def test_scipy2(img_input: Image.Image) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
# minimum percentage of image coverage each colour needs to be, lower for more colours
threshold_pixel_percentage: float = 0.02
nb_colours: int = 20
nb_colours_under_threshold: int = nb_colours
centroids: Optional[np.ndarray] = None
qnt: Optional[np.ndarray] = None
flat_img_sample: np.ndarray = sklearn.utils.shuffle(flat_img, random_state=0)[:1000]
while nb_colours_under_threshold > 0:
# performing the clustering
centroids, _ = scipy.cluster.vq.kmeans(flat_img_sample, nb_colours)
# quantization
qnt, _ = scipy.cluster.vq.vq(flat_img, centroids)
nb_colours, nb_colours_under_threshold = update_nb_colours(
qnt, nb_pixels, threshold_pixel_percentage, nb_colours # , flat_img
)
# reshaping the result of the quantization
centers_idx: np.ndarray = np.reshape(qnt, (img.shape[0], img.shape[1]))
return process_result(centroids, centers_idx, img.shape)
def test_sklearn_kmeans(img_input: Image.Image) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
# minimum percentage of image coverage each colour needs to be, lower for more colours
threshold_pixel_percentage: float = 0.02
nb_colours: int = 20
nb_colours_under_threshold: int = nb_colours
center: Optional[np.ndarray] = None
label: Optional[np.ndarray] = None
while nb_colours_under_threshold > 0:
kmeans_instance: KMeans = KMeans(n_clusters=nb_colours, random_state=0).fit(
flat_img
)
label = kmeans_instance.labels_
center = kmeans_instance.cluster_centers_
nb_colours, nb_colours_under_threshold = update_nb_colours(
label, nb_pixels, threshold_pixel_percentage, nb_colours # , flat_img
)
return process_result(center, label, img.shape)
def test_sklearn_iter(
img_input: Image.Image, constructor: Callable
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
# minimum percentage of image coverage each colour needs to be, lower for more colours
threshold_pixel_percentage: float = 0.02
nb_colours: int = 20
nb_colours_under_threshold: int = nb_colours
center: Optional[np.ndarray] = None
label: Optional[np.ndarray] = None
flat_img_sample: np.ndarray = sklearn.utils.shuffle(flat_img, random_state=0)[:1000]
while nb_colours_under_threshold > 0:
kmeans_instance: Union[KMeans, MiniBatchKMeans] = constructor(
n_clusters=nb_colours, random_state=42
).fit(flat_img_sample)
center = kmeans_instance.cluster_centers_
label = kmeans_instance.predict(flat_img)
nb_colours, nb_colours_under_threshold = update_nb_colours(
label, nb_pixels, threshold_pixel_percentage, nb_colours # , flat_img
)
return process_result(center, label, img.shape)
def test_sklearn_kmeans2(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_sklearn_iter(img_input, KMeans)
def test_sklearn_mini_batch_kmeans(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_sklearn_iter(img_input, MiniBatchKMeans)
def test_sklearn_mean_shift(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
center: np.ndarray
label: np.ndarray
flat_img_sample: np.ndarray = sklearn.utils.shuffle(flat_img, random_state=0)[:1000]
clusterer_instance: MeanShift = MeanShift().fit(flat_img_sample)
center = clusterer_instance.cluster_centers_
label = clusterer_instance.predict(flat_img)
return process_result(center, label, img.shape)
def process_pycluster_result(
flat_img: np.ndarray,
clusters: [[int]],
representatives: [[float]],
shape: Tuple[int, int, int],
conversion_method: int = cv2.COLOR_BGR2RGB,
) -> Tuple[Type[Image.Image], np.ndarray]:
representatives: np.ndarray = np.uint8(representatives)
for index_cluster, cluster in enumerate(clusters):
for pixel in cluster:
flat_img[pixel] = representatives[index_cluster]
quantized_img: np.ndarray = np.uint8(flat_img.reshape(shape))
quantized_img = cv2.cvtColor(quantized_img, conversion_method)
representatives = cv2.cvtColor(
np.expand_dims(representatives, axis=0), conversion_method
)[0]
return Image.fromarray(quantized_img), representatives
def test_pycluster_threshold(
img_input: Image.Image, func: Callable
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
# Prepare algorithm's parameters.
max_clusters: int = 20
threshold: float = 15
# this function gave me the best result with the lest colours
clusterer: bsas.bsas = func(
flat_img,
max_clusters,
threshold,
metric=distance_metric(type_metric.CHI_SQUARE),
)
clusterer.process()
clusters: [[int]] = clusterer.get_clusters()
representatives: [[float]] = clusterer.get_representatives()
return process_pycluster_result(flat_img, clusters, representatives, img.shape)
def test_pycluster_bsas(img_input: Image.Image) -> Tuple[Type[Image.Image], np.ndarray]:
return test_pycluster_threshold(img_input, bsas.bsas)
def test_pycluster_mbsas(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_pycluster_threshold(img_input, mbsas.mbsas)
def test_pycluster_neighbours(
img_input: Image.Image, func: Callable
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
# Prepare algorithm's parameters.
eps: float = 0.7
neighbors: int = len(flat_img) // 1000
clusterer: Union[dbscan.dbscan, optics.optics] = func(flat_img, eps, neighbors)
clusterer.process()
clusters: [[int]] = clusterer.get_clusters()
representatives: np.ndarray = np.asarray(
[
np.mean([flat_img[pixel] for pixel in cluster], axis=0)
for cluster in clusters
]
)
return process_pycluster_result(flat_img, clusters, representatives, img.shape)
def test_pycluster_dbscan(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_pycluster_neighbours(img_input, dbscan.dbscan)
def test_pycluster_optics(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_pycluster_neighbours(img_input, optics.optics)
def test_pycluster_syncnet(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input, True)
# Prepare algorithm's parameters.
radius: float = 50
network: syncnet.syncnet = syncnet.syncnet(flat_img, radius)
clusterer: syncnet.syncnet_analyser = network.process()
clusters: [[int]] = clusterer.allocate_clusters()
representatives: np.ndarray = np.asarray(
[
np.mean([flat_img[pixel] for pixel in cluster], axis=0)
for cluster in clusters
]
)
return process_pycluster_result(flat_img, clusters, representatives, img.shape)
def test_pycluster_syncsom(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input, True)
# Prepare algorithm's parameters.
radius: float = 0.001
rows: int = 2
cols: int = 2
clusterer: syncsom.syncsom = syncsom.syncsom(flat_img, rows, cols, radius)
clusterer.process()
clusters: [[int]] = clusterer.get_clusters()
representatives: np.ndarray = np.asarray(
[
np.mean([flat_img[pixel] for pixel in cluster], axis=0)
for cluster in clusters
]
)
return process_pycluster_result(flat_img, clusters, representatives, img.shape)
def test_pycluster_2threshold(
img_input: Image.Image, func: Callable
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
# Prepare algorithm's parameters.
threshold1: float = 70
threshold2: float = 120
# Manhattan, although not particularly good for colour distance, gave me the best results
clusterer: ttsas.ttsas = func(
flat_img, threshold1, threshold2, metric=distance_metric(type_metric.MANHATTAN)
)
clusterer.process()
clusters: [[int]] = clusterer.get_clusters()
representatives: [[float]] = clusterer.get_representatives()
return process_pycluster_result(flat_img, clusters, representatives, img.shape)
def test_pycluster_ttsas(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_pycluster_2threshold(img_input, ttsas.ttsas)
def test_pycluster_xmeans(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
amount_initial_centers: int = 2
initial_centers: [np.ndarray] = center_initializer.kmeans_plusplus_initializer(
flat_img, amount_initial_centers
).initialize()
max_clusters: int = 20
clusterer: xmeans.xmeans = xmeans.xmeans(flat_img, initial_centers, max_clusters)
clusterer.process()
clusters: [[int]] = clusterer.get_clusters()
representatives: [[float]] = clusterer.get_centers()
return process_pycluster_result(flat_img, clusters, representatives, img.shape)
def test_pycluster_k(
img_input: Image.Image, func: Callable, center_func_str: str
) -> Tuple[Type[Image.Image], np.ndarray]:
img, nb_pixels, flat_img = get_img_data(img_input)
kmin: int = 2
kmax: int = 20
elbow_instance: elbow.elbow = elbow.elbow(flat_img, kmin, kmax)
elbow_instance.process()
amount_clusters: int = elbow_instance.get_amount()
centers: [np.ndarray] = center_initializer.kmeans_plusplus_initializer(
flat_img, amount_clusters
).initialize()
clusterer: Union[kmeans.kmeans, kmedians.kmedians] = func(flat_img, centers)
clusterer.process()
clusters: [[int]] = clusterer.get_clusters()
representatives: [[float]] = eval("clusterer." + center_func_str + "()")
return process_pycluster_result(flat_img, clusters, representatives, img.shape)
def test_pycluster_kmeans(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_pycluster_k(img_input, kmeans.kmeans, "get_centers")
def test_pycluster_kmedians(
img_input: Image.Image
) -> Tuple[Type[Image.Image], np.ndarray]:
return test_pycluster_k(img_input, kmedians.kmedians, "get_medians")
def create_colour_list_image(
colours_list: [[int]], img_name: str, quantize_function_name: str
) -> None:
h, w = (25, 20)
colour_img: Image.Image = Image.new("RGB", (w * len(colours_list), h))
colours_list: [Tuple[int, int, int]] = sum(
[[tuple(colour)] * w for colour in colours_list] * h, []
)
colour_img.putdata(colours_list)
colour_img.save(
f"./imgs_results/test_colours_{img_name}_{quantize_function_name}.png"
)
def create_images_results(imgs: [str], quantize_functions: [str]) -> None:
for img_name in imgs:
_img: Image.Image = Image.open(f"imgs/{img_name}.jpg")
for quantize_function_name in quantize_functions:
func_name = "test_" + quantize_function_name
quantized_img, colours_list = eval(f"{func_name}(_img)")
print(
f"{img_name} - {quantize_function_name} nb colours : {len(colours_list)}"
)
quantized_img.save(
f"./imgs_results/test_img_{img_name}_{quantize_function_name}.png"
)
create_colour_list_image(colours_list, img_name, quantize_function_name)
def benchmark(imgs: [str], quantize_functions: [str]) -> None:
for quantize_function_name in quantize_functions:
img: Image.Image = Image.open(f"imgs/{imgs[0]}.jpg")
func_name = "test_" + quantize_function_name
time = timeit.timeit(
func_name + "(img)",
number=10,
setup="from __main__ import " + func_name,
globals={"img": img},
)
print(f"{quantize_function_name} time : {time} s")
def test_all(imgs: [str], quantize_functions: [str]) -> None:
create_images_results(imgs, quantize_functions)
benchmark(imgs, quantize_functions)
if __name__ == "__main__":
test_all(
[
"hanif-mahmad-9aIz3Uz6xsk-unsplash",
"hanif-mahmad-eEwU2NCrqE8-unsplash",
"hanif-mahmad-g_Ajr_yG1YA-unsplash",
"hanif-mahmad-tA_ph2EjJkk-unsplash",
"hanif-mahmad-Zxjdu-d7vWs-unsplash",
"simon-launay-0OYeIqq1IC0-unsplash",
"simon-launay--QC-lCW6yCI-unsplash",
"simon-launay-a9Sbz8_hW8Q-unsplash",
"simon-launay-eSlCg_gGNCg-unsplash",
"simon-launay-Igu6Ig9JthU-unsplash",
"simon-launay-IgYBZwOVm04-unsplash",
"simon-launay-lHVpa2WUb9k-unsplash",
"simon-launay-nYcAQhgpXRk-unsplash",
"simon-launay-pTaryUjCPkw-unsplash",
"simon-launay-RIyfkoXxWzc-unsplash",
"simon-launay-x9WpMb1t2Nc-unsplash",
],
[
"pillow_median_cut",
"pillow_maximum_coverage",
"pillow_fast_octree",
"opencv_rgb",
"opencv_hsv",
"opencv_lab",
"scipy",
"scipy2",
"sklearn_kmeans",
"sklearn_kmeans2",
"sklearn_mini_batch_kmeans",
"sklearn_mean_shift",
"pycluster_bsas",
"pycluster_mbsas",
# "pycluster_dbscan",
# "pycluster_optics",
"pycluster_syncnet",
"pycluster_syncsom",
"pycluster_ttsas",
"pycluster_xmeans",
"pycluster_kmeans",
"pycluster_kmedians",
],
)