Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/core/src/kmeans.cpp
16337 views
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
// By downloading, copying, installing or using the software you agree to this license.
6
// If you do not agree to this license, do not download, install,
7
// copy or use the software.
8
//
9
//
10
// License Agreement
11
// For Open Source Computer Vision Library
12
//
13
// Copyright (C) 2000-2018, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
16
// Third party copyrights are property of their respective owners.
17
//
18
// Redistribution and use in source and binary forms, with or without modification,
19
// are permitted provided that the following conditions are met:
20
//
21
// * Redistribution's of source code must retain the above copyright notice,
22
// this list of conditions and the following disclaimer.
23
//
24
// * Redistribution's in binary form must reproduce the above copyright notice,
25
// this list of conditions and the following disclaimer in the documentation
26
// and/or other materials provided with the distribution.
27
//
28
// * The name of the copyright holders may not be used to endorse or promote products
29
// derived from this software without specific prior written permission.
30
//
31
// This software is provided by the copyright holders and contributors "as is" and
32
// any express or implied warranties, including, but not limited to, the implied
33
// warranties of merchantability and fitness for a particular purpose are disclaimed.
34
// In no event shall the Intel Corporation or contributors be liable for any direct,
35
// indirect, incidental, special, exemplary, or consequential damages
36
// (including, but not limited to, procurement of substitute goods or services;
37
// loss of use, data, or profits; or business interruption) however caused
38
// and on any theory of liability, whether in contract, strict liability,
39
// or tort (including negligence or otherwise) arising in any way out of
40
// the use of this software, even if advised of the possibility of such damage.
41
//
42
//M*/
43
44
#include "precomp.hpp"
45
#include <opencv2/core/utils/configuration.private.hpp>
46
#include <opencv2/core/hal/hal.hpp>
47
48
////////////////////////////////////////// kmeans ////////////////////////////////////////////
49
50
namespace cv
51
{
52
53
static int CV_KMEANS_PARALLEL_GRANULARITY = (int)utils::getConfigurationParameterSizeT("OPENCV_KMEANS_PARALLEL_GRANULARITY", 1000);
54
55
static void generateRandomCenter(int dims, const Vec2f* box, float* center, RNG& rng)
56
{
57
float margin = 1.f/dims;
58
for (int j = 0; j < dims; j++)
59
center[j] = ((float)rng*(1.f+margin*2.f)-margin)*(box[j][1] - box[j][0]) + box[j][0];
60
}
61
62
class KMeansPPDistanceComputer : public ParallelLoopBody
63
{
64
public:
65
KMeansPPDistanceComputer(float *tdist2_, const Mat& data_, const float *dist_, int ci_) :
66
tdist2(tdist2_), data(data_), dist(dist_), ci(ci_)
67
{ }
68
69
void operator()( const cv::Range& range ) const CV_OVERRIDE
70
{
71
CV_TRACE_FUNCTION();
72
const int begin = range.start;
73
const int end = range.end;
74
const int dims = data.cols;
75
76
for (int i = begin; i<end; i++)
77
{
78
tdist2[i] = std::min(hal::normL2Sqr_(data.ptr<float>(i), data.ptr<float>(ci), dims), dist[i]);
79
}
80
}
81
82
private:
83
KMeansPPDistanceComputer& operator=(const KMeansPPDistanceComputer&); // = delete
84
85
float *tdist2;
86
const Mat& data;
87
const float *dist;
88
const int ci;
89
};
90
91
/*
92
k-means center initialization using the following algorithm:
93
Arthur & Vassilvitskii (2007) k-means++: The Advantages of Careful Seeding
94
*/
95
static void generateCentersPP(const Mat& data, Mat& _out_centers,
96
int K, RNG& rng, int trials)
97
{
98
CV_TRACE_FUNCTION();
99
const int dims = data.cols, N = data.rows;
100
cv::AutoBuffer<int, 64> _centers(K);
101
int* centers = &_centers[0];
102
cv::AutoBuffer<float, 0> _dist(N*3);
103
float* dist = &_dist[0], *tdist = dist + N, *tdist2 = tdist + N;
104
double sum0 = 0;
105
106
centers[0] = (unsigned)rng % N;
107
108
for (int i = 0; i < N; i++)
109
{
110
dist[i] = hal::normL2Sqr_(data.ptr<float>(i), data.ptr<float>(centers[0]), dims);
111
sum0 += dist[i];
112
}
113
114
for (int k = 1; k < K; k++)
115
{
116
double bestSum = DBL_MAX;
117
int bestCenter = -1;
118
119
for (int j = 0; j < trials; j++)
120
{
121
double p = (double)rng*sum0;
122
int ci = 0;
123
for (; ci < N - 1; ci++)
124
{
125
p -= dist[ci];
126
if (p <= 0)
127
break;
128
}
129
130
parallel_for_(Range(0, N),
131
KMeansPPDistanceComputer(tdist2, data, dist, ci),
132
(double)divUp((size_t)(dims * N), CV_KMEANS_PARALLEL_GRANULARITY));
133
double s = 0;
134
for (int i = 0; i < N; i++)
135
{
136
s += tdist2[i];
137
}
138
139
if (s < bestSum)
140
{
141
bestSum = s;
142
bestCenter = ci;
143
std::swap(tdist, tdist2);
144
}
145
}
146
centers[k] = bestCenter;
147
sum0 = bestSum;
148
std::swap(dist, tdist);
149
}
150
151
for (int k = 0; k < K; k++)
152
{
153
const float* src = data.ptr<float>(centers[k]);
154
float* dst = _out_centers.ptr<float>(k);
155
for (int j = 0; j < dims; j++)
156
dst[j] = src[j];
157
}
158
}
159
160
template<bool onlyDistance>
161
class KMeansDistanceComputer : public ParallelLoopBody
162
{
163
public:
164
KMeansDistanceComputer( double *distances_,
165
int *labels_,
166
const Mat& data_,
167
const Mat& centers_)
168
: distances(distances_),
169
labels(labels_),
170
data(data_),
171
centers(centers_)
172
{
173
}
174
175
void operator()(const Range& range) const CV_OVERRIDE
176
{
177
CV_TRACE_FUNCTION();
178
const int begin = range.start;
179
const int end = range.end;
180
const int K = centers.rows;
181
const int dims = centers.cols;
182
183
for (int i = begin; i < end; ++i)
184
{
185
const float *sample = data.ptr<float>(i);
186
if (onlyDistance)
187
{
188
const float* center = centers.ptr<float>(labels[i]);
189
distances[i] = hal::normL2Sqr_(sample, center, dims);
190
continue;
191
}
192
else
193
{
194
int k_best = 0;
195
double min_dist = DBL_MAX;
196
197
for (int k = 0; k < K; k++)
198
{
199
const float* center = centers.ptr<float>(k);
200
const double dist = hal::normL2Sqr_(sample, center, dims);
201
202
if (min_dist > dist)
203
{
204
min_dist = dist;
205
k_best = k;
206
}
207
}
208
209
distances[i] = min_dist;
210
labels[i] = k_best;
211
}
212
}
213
}
214
215
private:
216
KMeansDistanceComputer& operator=(const KMeansDistanceComputer&); // = delete
217
218
double *distances;
219
int *labels;
220
const Mat& data;
221
const Mat& centers;
222
};
223
224
}
225
226
double cv::kmeans( InputArray _data, int K,
227
InputOutputArray _bestLabels,
228
TermCriteria criteria, int attempts,
229
int flags, OutputArray _centers )
230
{
231
CV_INSTRUMENT_REGION();
232
const int SPP_TRIALS = 3;
233
Mat data0 = _data.getMat();
234
const bool isrow = data0.rows == 1;
235
const int N = isrow ? data0.cols : data0.rows;
236
const int dims = (isrow ? 1 : data0.cols)*data0.channels();
237
const int type = data0.depth();
238
239
attempts = std::max(attempts, 1);
240
CV_Assert( data0.dims <= 2 && type == CV_32F && K > 0 );
241
CV_Assert( N >= K );
242
243
Mat data(N, dims, CV_32F, data0.ptr(), isrow ? dims * sizeof(float) : static_cast<size_t>(data0.step));
244
245
_bestLabels.create(N, 1, CV_32S, -1, true);
246
247
Mat _labels, best_labels = _bestLabels.getMat();
248
if (flags & CV_KMEANS_USE_INITIAL_LABELS)
249
{
250
CV_Assert( (best_labels.cols == 1 || best_labels.rows == 1) &&
251
best_labels.cols*best_labels.rows == N &&
252
best_labels.type() == CV_32S &&
253
best_labels.isContinuous());
254
best_labels.reshape(1, N).copyTo(_labels);
255
for (int i = 0; i < N; i++)
256
{
257
CV_Assert((unsigned)_labels.at<int>(i) < (unsigned)K);
258
}
259
}
260
else
261
{
262
if (!((best_labels.cols == 1 || best_labels.rows == 1) &&
263
best_labels.cols*best_labels.rows == N &&
264
best_labels.type() == CV_32S &&
265
best_labels.isContinuous()))
266
{
267
_bestLabels.create(N, 1, CV_32S);
268
best_labels = _bestLabels.getMat();
269
}
270
_labels.create(best_labels.size(), best_labels.type());
271
}
272
int* labels = _labels.ptr<int>();
273
274
Mat centers(K, dims, type), old_centers(K, dims, type), temp(1, dims, type);
275
cv::AutoBuffer<int, 64> counters(K);
276
cv::AutoBuffer<double, 64> dists(N);
277
RNG& rng = theRNG();
278
279
if (criteria.type & TermCriteria::EPS)
280
criteria.epsilon = std::max(criteria.epsilon, 0.);
281
else
282
criteria.epsilon = FLT_EPSILON;
283
criteria.epsilon *= criteria.epsilon;
284
285
if (criteria.type & TermCriteria::COUNT)
286
criteria.maxCount = std::min(std::max(criteria.maxCount, 2), 100);
287
else
288
criteria.maxCount = 100;
289
290
if (K == 1)
291
{
292
attempts = 1;
293
criteria.maxCount = 2;
294
}
295
296
cv::AutoBuffer<Vec2f, 64> box(dims);
297
if (!(flags & KMEANS_PP_CENTERS))
298
{
299
{
300
const float* sample = data.ptr<float>(0);
301
for (int j = 0; j < dims; j++)
302
box[j] = Vec2f(sample[j], sample[j]);
303
}
304
for (int i = 1; i < N; i++)
305
{
306
const float* sample = data.ptr<float>(i);
307
for (int j = 0; j < dims; j++)
308
{
309
float v = sample[j];
310
box[j][0] = std::min(box[j][0], v);
311
box[j][1] = std::max(box[j][1], v);
312
}
313
}
314
}
315
316
double best_compactness = DBL_MAX;
317
for (int a = 0; a < attempts; a++)
318
{
319
double compactness = 0;
320
321
for (int iter = 0; ;)
322
{
323
double max_center_shift = iter == 0 ? DBL_MAX : 0.0;
324
325
swap(centers, old_centers);
326
327
if (iter == 0 && (a > 0 || !(flags & KMEANS_USE_INITIAL_LABELS)))
328
{
329
if (flags & KMEANS_PP_CENTERS)
330
generateCentersPP(data, centers, K, rng, SPP_TRIALS);
331
else
332
{
333
for (int k = 0; k < K; k++)
334
generateRandomCenter(dims, box.data(), centers.ptr<float>(k), rng);
335
}
336
}
337
else
338
{
339
// compute centers
340
centers = Scalar(0);
341
for (int k = 0; k < K; k++)
342
counters[k] = 0;
343
344
for (int i = 0; i < N; i++)
345
{
346
const float* sample = data.ptr<float>(i);
347
int k = labels[i];
348
float* center = centers.ptr<float>(k);
349
for (int j = 0; j < dims; j++)
350
center[j] += sample[j];
351
counters[k]++;
352
}
353
354
for (int k = 0; k < K; k++)
355
{
356
if (counters[k] != 0)
357
continue;
358
359
// if some cluster appeared to be empty then:
360
// 1. find the biggest cluster
361
// 2. find the farthest from the center point in the biggest cluster
362
// 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster.
363
int max_k = 0;
364
for (int k1 = 1; k1 < K; k1++)
365
{
366
if (counters[max_k] < counters[k1])
367
max_k = k1;
368
}
369
370
double max_dist = 0;
371
int farthest_i = -1;
372
float* base_center = centers.ptr<float>(max_k);
373
float* _base_center = temp.ptr<float>(); // normalized
374
float scale = 1.f/counters[max_k];
375
for (int j = 0; j < dims; j++)
376
_base_center[j] = base_center[j]*scale;
377
378
for (int i = 0; i < N; i++)
379
{
380
if (labels[i] != max_k)
381
continue;
382
const float* sample = data.ptr<float>(i);
383
double dist = hal::normL2Sqr_(sample, _base_center, dims);
384
385
if (max_dist <= dist)
386
{
387
max_dist = dist;
388
farthest_i = i;
389
}
390
}
391
392
counters[max_k]--;
393
counters[k]++;
394
labels[farthest_i] = k;
395
396
const float* sample = data.ptr<float>(farthest_i);
397
float* cur_center = centers.ptr<float>(k);
398
for (int j = 0; j < dims; j++)
399
{
400
base_center[j] -= sample[j];
401
cur_center[j] += sample[j];
402
}
403
}
404
405
for (int k = 0; k < K; k++)
406
{
407
float* center = centers.ptr<float>(k);
408
CV_Assert( counters[k] != 0 );
409
410
float scale = 1.f/counters[k];
411
for (int j = 0; j < dims; j++)
412
center[j] *= scale;
413
414
if (iter > 0)
415
{
416
double dist = 0;
417
const float* old_center = old_centers.ptr<float>(k);
418
for (int j = 0; j < dims; j++)
419
{
420
double t = center[j] - old_center[j];
421
dist += t*t;
422
}
423
max_center_shift = std::max(max_center_shift, dist);
424
}
425
}
426
}
427
428
bool isLastIter = (++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon);
429
430
if (isLastIter)
431
{
432
// don't re-assign labels to avoid creation of empty clusters
433
parallel_for_(Range(0, N), KMeansDistanceComputer<true>(dists.data(), labels, data, centers), (double)divUp((size_t)(dims * N), CV_KMEANS_PARALLEL_GRANULARITY));
434
compactness = sum(Mat(Size(N, 1), CV_64F, &dists[0]))[0];
435
break;
436
}
437
else
438
{
439
// assign labels
440
parallel_for_(Range(0, N), KMeansDistanceComputer<false>(dists.data(), labels, data, centers), (double)divUp((size_t)(dims * N * K), CV_KMEANS_PARALLEL_GRANULARITY));
441
}
442
}
443
444
if (compactness < best_compactness)
445
{
446
best_compactness = compactness;
447
if (_centers.needed())
448
{
449
if (_centers.fixedType() && _centers.channels() == dims)
450
centers.reshape(dims).copyTo(_centers);
451
else
452
centers.copyTo(_centers);
453
}
454
_labels.copyTo(best_labels);
455
}
456
}
457
458
return best_compactness;
459
}
460
461