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
/*
By downloading, copying, installing or using the software you agree to this license.
If you do not agree to this license, do not download, install,
copy or use the software.
License Agreement
For Open Source Computer Vision Library
(3-clause BSD License)
Copyright (C) 2000-2016, Intel Corporation, all rights reserved.
Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved.
Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved.
Copyright (C) 2015-2016, Itseez Inc., all rights reserved.
Third party copyrights are property of their respective owners.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the copyright holders nor the names of the contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are disclaimed.
In no event shall copyright holders or contributors be liable for any direct,
indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused
and on any theory of liability, whether in contract, strict liability,
or tort (including negligence or otherwise) arising in any way out of
the use of this software, even if advised of the possibility of such damage.
*/
/*
Contributed by Gregor Kovalcik <gregor dot kovalcik at gmail dot com>
based on code provided by Martin Krulis, Jakub Lokoc and Tomas Skopal.
References:
Martin Krulis, Jakub Lokoc, Tomas Skopal.
Efficient Extraction of Clustering-Based Feature Signatures Using GPU Architectures.
Multimedia tools and applications, 75(13), pp.: 8071�8103, Springer, ISSN: 1380-7501, 2016
Christian Beecks, Merih Seran Uysal, Thomas Seidl.
Signature quadratic form distance.
In Proceedings of the ACM International Conference on Image and Video Retrieval, pages 438-445.
ACM, 2010.
*/
#include "precomp.hpp"
#include "pct_signatures/constants.hpp"
#include "pct_signatures/pct_sampler.hpp"
#include "pct_signatures/pct_clusterizer.hpp"
using namespace cv::xfeatures2d::pct_signatures;
namespace cv
{
namespace xfeatures2d
{
namespace pct_signatures
{
class PCTSignatures_Impl : public PCTSignatures
{
public:
PCTSignatures_Impl(const std::vector<Point2f>& initSamplingPoints, int initSeedCount)
{
if (initSamplingPoints.size() == 0)
{
CV_Error(Error::StsBadArg, "No sampling points provided!");
}
if (initSeedCount <= 0)
{
CV_Error(Error::StsBadArg, "Not enough initial seeds, at least 1 required.");
}
mSampler = PCTSampler::create(initSamplingPoints);
initSeedCount = std::min(initSeedCount, (int)initSamplingPoints.size());
std::vector<int> initClusterSeedIndexes = pickRandomClusterSeedIndexes(initSeedCount);
mClusterizer = PCTClusterizer::create(initClusterSeedIndexes);
}
PCTSignatures_Impl(
const std::vector<Point2f>& initSamplingPoints,
const std::vector<int>& initClusterSeedIndexes)
{
if (initSamplingPoints.size() == 0)
{
CV_Error(Error::StsBadArg, "No sampling points provided!");
}
if (initClusterSeedIndexes.size() == 0)
{
CV_Error(Error::StsBadArg, "Not enough initial seeds, at least 1 required.");
}
if (initClusterSeedIndexes.size() > initSamplingPoints.size())
{
CV_Error(Error::StsBadArg, "Too much cluster seeds or not enough sampling points.");
}
for (int iCluster = 0; iCluster < (int)(initClusterSeedIndexes.size()); iCluster++)
{
if (initClusterSeedIndexes[iCluster] < 0
|| initClusterSeedIndexes[iCluster] >= (int)(initSamplingPoints.size()))
{
CV_Error(Error::StsBadArg,
"Initial cluster seed indexes contain an index outside the range of the sampling point list.");
}
}
mSampler = PCTSampler::create(initSamplingPoints);
mClusterizer = PCTClusterizer::create(initClusterSeedIndexes);
}
void computeSignature(InputArray image, OutputArray signature) const CV_OVERRIDE;
void computeSignatures(const std::vector<Mat>& images, std::vector<Mat>& signatures) const CV_OVERRIDE;
void getGrayscaleBitmap(OutputArray _grayscaleBitmap, bool normalize) const;
/**** sampler ****/
int getSampleCount() const CV_OVERRIDE { return mSampler->getGrayscaleBits(); }
int getGrayscaleBits() const CV_OVERRIDE { return mSampler->getGrayscaleBits(); }
int getWindowRadius() const CV_OVERRIDE { return mSampler->getWindowRadius(); }
float getWeightX() const CV_OVERRIDE { return mSampler->getWeightX(); }
float getWeightY() const CV_OVERRIDE { return mSampler->getWeightY(); }
float getWeightL() const CV_OVERRIDE { return mSampler->getWeightL(); }
float getWeightA() const CV_OVERRIDE { return mSampler->getWeightA(); }
float getWeightB() const CV_OVERRIDE { return mSampler->getWeightB(); }
float getWeightContrast() const CV_OVERRIDE { return mSampler->getWeightContrast(); }
float getWeightEntropy() const CV_OVERRIDE { return mSampler->getWeightEntropy(); }
std::vector<Point2f> getSamplingPoints() const CV_OVERRIDE { return mSampler->getSamplingPoints(); }
void setGrayscaleBits(int grayscaleBits) CV_OVERRIDE { mSampler->setGrayscaleBits(grayscaleBits); }
void setWindowRadius(int windowRadius) CV_OVERRIDE { mSampler->setWindowRadius(windowRadius); }
void setWeightX(float weight) CV_OVERRIDE { mSampler->setWeightX(weight); }
void setWeightY(float weight) CV_OVERRIDE { mSampler->setWeightY(weight); }
void setWeightL(float weight) CV_OVERRIDE { mSampler->setWeightL(weight); }
void setWeightA(float weight) CV_OVERRIDE { mSampler->setWeightA(weight); }
void setWeightB(float weight) CV_OVERRIDE { mSampler->setWeightB(weight); }
void setWeightContrast(float weight) CV_OVERRIDE { mSampler->setWeightContrast(weight); }
void setWeightEntropy(float weight) CV_OVERRIDE { mSampler->setWeightEntropy(weight); }
void setWeight(int idx, float value) CV_OVERRIDE { mSampler->setWeight(idx, value); }
void setWeights(const std::vector<float>& weights) CV_OVERRIDE { mSampler->setWeights(weights); }
void setTranslation(int idx, float value) CV_OVERRIDE { mSampler->setTranslation(idx, value); }
void setTranslations(const std::vector<float>& translations) CV_OVERRIDE { mSampler->setTranslations(translations); }
void setSamplingPoints(std::vector<Point2f> samplingPoints) CV_OVERRIDE { mSampler->setSamplingPoints(samplingPoints); }
/**** clusterizer ****/
int getIterationCount() const CV_OVERRIDE { return mClusterizer->getIterationCount(); }
std::vector<int> getInitSeedIndexes() const CV_OVERRIDE { return mClusterizer->getInitSeedIndexes(); }
int getInitSeedCount() const CV_OVERRIDE { return (int)mClusterizer->getInitSeedIndexes().size(); }
int getMaxClustersCount() const CV_OVERRIDE { return mClusterizer->getMaxClustersCount(); }
int getClusterMinSize() const CV_OVERRIDE { return mClusterizer->getClusterMinSize(); }
float getJoiningDistance() const CV_OVERRIDE { return mClusterizer->getJoiningDistance(); }
float getDropThreshold() const CV_OVERRIDE { return mClusterizer->getDropThreshold(); }
int getDistanceFunction() const CV_OVERRIDE
{ return mClusterizer->getDistanceFunction(); }
void setIterationCount(int iterations) CV_OVERRIDE { mClusterizer->setIterationCount(iterations); }
void setInitSeedIndexes(std::vector<int> initSeedIndexes) CV_OVERRIDE
{ mClusterizer->setInitSeedIndexes(initSeedIndexes); }
void setMaxClustersCount(int maxClusters) CV_OVERRIDE { mClusterizer->setMaxClustersCount(maxClusters); }
void setClusterMinSize(int clusterMinSize) CV_OVERRIDE { mClusterizer->setClusterMinSize(clusterMinSize); }
void setJoiningDistance(float joiningDistance) CV_OVERRIDE { mClusterizer->setJoiningDistance(joiningDistance); }
void setDropThreshold(float dropThreshold) CV_OVERRIDE { mClusterizer->setDropThreshold(dropThreshold); }
void setDistanceFunction(int distanceFunction) CV_OVERRIDE
{ mClusterizer->setDistanceFunction(distanceFunction); }
private:
/**
* @brief Samples used for sampling the input image and producing list of samples.
*/
Ptr<PCTSampler> mSampler;
/**
* @brief Clusterizer using k-means algorithm to produce list of centroids from sampled points - the image signature.
*/
Ptr<PCTClusterizer> mClusterizer;
/**
* @brief Creates vector of random indexes of sampling points
* which will be used as initial centroids for k-means clusterization.
* @param initSeedCount Number of indexes of initial centroids to be produced.
* @return The generated vector of random indexes.
*/
static std::vector<int> pickRandomClusterSeedIndexes(int initSeedCount)
{
std::vector<int> seedIndexes;
for (int iSeed = 0; iSeed < initSeedCount; iSeed++)
{
seedIndexes.push_back(iSeed);
}
randShuffle(seedIndexes);
return seedIndexes;
}
};
/**
* @brief Class implementing parallel computing of signatures for multiple images.
*/
class Parallel_computeSignatures : public ParallelLoopBody
{
private:
const PCTSignatures* mPctSignaturesAlgorithm;
const std::vector<Mat>* mImages;
std::vector<Mat>* mSignatures;
public:
Parallel_computeSignatures(
const PCTSignatures* pctSignaturesAlgorithm,
const std::vector<Mat>* images,
std::vector<Mat>* signatures)
: mPctSignaturesAlgorithm(pctSignaturesAlgorithm),
mImages(images),
mSignatures(signatures)
{
mSignatures->resize(images->size());
}
void operator()(const Range& range) const CV_OVERRIDE
{
for (int i = range.start; i < range.end; i++)
{
mPctSignaturesAlgorithm->computeSignature((*mImages)[i], (*mSignatures)[i]);
}
}
};
/**
* @brief Computes signature for one image.
*/
void PCTSignatures_Impl::computeSignature(InputArray _image, OutputArray _signature) const
{
if (_image.empty())
{
_signature.create(_image.size(), CV_32FC1);
return;
}
Mat image = _image.getMat();
CV_Assert(image.depth() == CV_8U);
// TODO: OpenCL
//if (ocl::useOpenCL())
//{
//}
// sample features
Mat samples;
mSampler->sample(image, samples); // HOT PATH: 40%
// kmeans clusterize, use feature samples, produce signature clusters
Mat signature;
mClusterizer->clusterize(samples, signature); // HOT PATH: 60%
// set result
_signature.create(signature.size(), signature.type());
Mat result = _signature.getMat();
signature.copyTo(result);
}
/**
* @brief Parallel function computing signatures for multiple images.
*/
void PCTSignatures_Impl::computeSignatures(const std::vector<Mat>& images, std::vector<Mat>& signatures) const
{
parallel_for_(Range(0, (int)images.size()), Parallel_computeSignatures(this, &images, &signatures));
}
} // end of namespace pct_signatures
Ptr<PCTSignatures> PCTSignatures::create(
const int initSampleCount,
const int initSeedCount,
const int pointDistribution)
{
std::vector<Point2f> initPoints;
generateInitPoints(initPoints, initSampleCount, pointDistribution);
return create(initPoints, initSeedCount);
}
Ptr<PCTSignatures> PCTSignatures::create(
const std::vector<Point2f>& initPoints,
const int initSeedCount)
{
return makePtr<PCTSignatures_Impl>(initPoints, initSeedCount);
}
Ptr<PCTSignatures> PCTSignatures::create(
const std::vector<Point2f>& initPoints,
const std::vector<int>& initClusterSeedIndexes)
{
return makePtr<PCTSignatures_Impl>(initPoints, initClusterSeedIndexes);
}
void PCTSignatures::drawSignature(
InputArray _source,
InputArray _signature,
OutputArray _result,
float radiusToShorterSideRatio,
int borderThickness)
{
// check source
if (_source.empty())
{
return;
}
Mat source = _source.getMat();
// create result
_result.create(source.size(), source.type());
Mat result = _result.getMat();
source.copyTo(result);
// check signature
if (_signature.empty())
{
return;
}
Mat signature = _signature.getMat();
if (signature.type() != CV_32F || signature.cols != SIGNATURE_DIMENSION)
{
CV_Error_(Error::StsBadArg, ("Invalid signature format. Type must be CV_32F and signature.cols must be %d.", SIGNATURE_DIMENSION));
}
// compute max radius using given ratio of shorter image side
float maxRadius = ((source.rows < source.cols) ? source.rows : source.cols) * radiusToShorterSideRatio;
// draw signature
for (int i = 0; i < signature.rows; i++)
{
Vec3f labColor(
signature.at<float>(i, L_IDX) * L_COLOR_RANGE, // convert Lab pixel to BGR
signature.at<float>(i, A_IDX) * A_COLOR_RANGE,
signature.at<float>(i, B_IDX) * B_COLOR_RANGE);
Mat labPixel(1, 1, CV_32FC3);
labPixel.at<Vec3f>(0, 0) = labColor;
Mat rgbPixel;
cvtColor(labPixel, rgbPixel, COLOR_Lab2BGR);
rgbPixel.convertTo(rgbPixel, CV_8UC3, 255);
Vec3b rgbColor = rgbPixel.at<Vec3b>(0, 0);
// precompute variables
Point center((int)(signature.at<float>(i, X_IDX) * source.cols), (int)(signature.at<float>(i, Y_IDX) * source.rows));
int radius = (int)(maxRadius * signature.at<float>(i, WEIGHT_IDX));
Vec3b borderColor(0, 0, 0);
// draw filled circle
circle(result, center, radius, rgbColor, -1);
// draw circle outline
circle(result, center, radius, borderColor, borderThickness);
}
}
void PCTSignatures::generateInitPoints(
std::vector<Point2f>& initPoints,
const int count,
const int pointDistribution)
{
RNG random;
random.state = getTickCount();
initPoints.resize(count);
switch (pointDistribution)
{
case UNIFORM:
for (int i = 0; i < count; i++)
{
// returns uniformly distributed float random number from [0, 1) range
initPoints[i] = (Point2f(random.uniform((float)0.0, (float)1.0), random.uniform((float)0.0, (float)1.0)));
}
break;
case REGULAR:
{
int gridSize = (int)ceil(sqrt((float)count));
const float step = 1.0f / gridSize;
const float halfStep = step / 2;
float x = halfStep;
float y = halfStep;
for (int i = 0; i < count; i++)
{
// returns regular grid
initPoints[i] = Point2f(x, y);
if ((i + 1) % gridSize == 0)
{
x = halfStep;
y += step;
}
else
{
x += step;
}
}
break;
}
case NORMAL:
for (int i = 0; i < count; i++)
{
// returns normally distributed float random number from (0, 1) range with mean 0.5
float sigma = 0.2f;
float x = (float)random.gaussian(sigma);
float y = (float)random.gaussian(sigma);
while (x <= -0.5f || x >= 0.5f)
x = (float)random.gaussian(sigma);
while (y <= -0.5f || y >= 0.5f)
y = (float)random.gaussian(sigma);
initPoints[i] = Point2f(x, y) + Point2f(0.5, 0.5);
}
break;
default:
CV_Error(Error::StsNotImplemented, "Generation of this init point distribution is not implemented!");
break;
}
}
} // end of namespace xfeatures2d
} // end of namespace cv