I wrote a c++ application that compares points matches from images (OpenSurf C++) but some times, 1 from some thousands开发者_运维知识库 of "getUniqueMatches", the application breaks in some point inside "getUniqueMatches". I has this log:
05/13/11 10:17:16: this->pointsA = 227
05/13/11 10:17:16: this->pointsB = 226
05/13/11 10:17:16: this->matches before = 0
05/13/11 10:17:16: 227 226 0 0.650000
05/13/11 10:17:16: Starting in getUniqueMatches
-- And here breaks, inside getUniqueMatches --
And this is the code:
inline bool findInVector(std::vector<int> v, int value) {
int size = v.size();
for(int i=0; i<size; i++) {
if(v[i] == value) {
return true;
}
}
return false;
}
void getUniqueMatches(IpVec &ipts1, IpVec &ipts2, IpPairVec &matches, float ratio) {
try {
wLog(f("%d %d %d %f", ipts1.size(), ipts2.size(), matches.size(), ratio));
float dist, d1, d2;
Ipoint *match;
matches.clear();
std::vector<int> matched;
wLog("Starting in getUniqueMatches");
// Breaks after here
int size = ipts1.size();
int size2 = ipts2.size();
for (int i = 0; i < size; i++) {
d1 = d2 = FLT_MAX;
int foundJ = -1;
for (unsigned int j = 0; j < size2; j++) {
dist = ipts1[i] - ipts2[j];
if (dist < d1 && !findInVector(matched, j)) {
d2 = d1;
d1 = dist;
match = &ipts2[j];
foundJ = j;
} else if (dist < d2) {
d2 = dist;
}
}
if (d1 / d2 < ratio) {
ipts1[i].dx = match->x - ipts1[i].x;
ipts1[i].dy = match->y - ipts1[i].y;
matches.push_back(std::make_pair(ipts1[i], *match));
matched.push_back(foundJ);
}
}
} catch(std::exception ex) {
wLog(f("Exception in getUniqueMatches: ", ex.what()));
return;
}
}
Only some times breaks here. I don't know what is happening, maybe something wrong? The application uses only 1 thread when executing this function. When extracting points uses 10 threads.
Using it on Centos5 (VPS). 2 Gb RAm 20% hd used Compiled using g++ (Performance mode), IDE used Netbeans. OpenCV, libcurl.
I suspect 2 things:
g++ compiler optimization. Use
-O2
or less;-O3
and beyond sometimes generate weird behavior especially concerning floating point operation.If reducing optimization does not fix the problem, I suggest changing
if (d1 / d2 < ratio)
to
if (d1 < double(ratio)*d2)
for avoiding division by zero (unlikely happen I think) and for better precision result.
Change
if (d1 / d2 < ratio) {
for
if(d2 > 0 && ...) {
I think that the problem was a division by zero, but was not throwing exceptions. :(
精彩评论