Affine2DEstimator.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. #include "StdAfx.h"
  2. #include "Affine2DEstimator.h"
  3. double geterr(CvMat* _err, CvMat* _mask){
  4. int i, count = _err->rows*_err->cols;
  5. uchar* mask = _mask->data.ptr;
  6. const float* err = _err->data.fl;
  7. double result = 0;
  8. for (i = 0; i < count; i++)
  9. if (mask[i])result += err[i];
  10. return result;
  11. }
  12. int Affine2DEstimator::findInliers(const CvMat* m1, const CvMat* m2,
  13. const CvMat* model, CvMat* _err,
  14. CvMat* _mask, double threshold)
  15. {
  16. int i, count = _err->rows*_err->cols, goodCount = 0;
  17. const float* err = _err->data.fl;
  18. uchar* mask = _mask->data.ptr;
  19. computeReprojError(m1, m2, model, _err);
  20. threshold *= threshold;
  21. for (i = 0; i < count; i++)
  22. goodCount += mask[i] = err[i] <= threshold;
  23. return goodCount;
  24. }
  25. void Affine2DEstimator::computeReprojError(const CvMat* m1, const CvMat* m2, const CvMat* model, CvMat* error)
  26. {
  27. int count = m1->rows * m1->cols;
  28. const CvPoint2D64f* from = reinterpret_cast<const CvPoint2D64f*>(m1->data.ptr);
  29. const CvPoint2D64f* to = reinterpret_cast<const CvPoint2D64f*>(m2->data.ptr);
  30. const double* F = model->data.db;
  31. float* err = error->data.fl;
  32. for (int i = 0; i < count; i++)
  33. {
  34. const CvPoint2D64f& f = from[i];
  35. const CvPoint2D64f& t = to[i];
  36. double a = F[0] * f.x + F[1] * f.y + F[2] - t.x;
  37. double b = F[3] * f.x + F[4] * f.y + F[5] - t.y;
  38. err[i] = (float)sqrt(a*a + b*b);
  39. }
  40. }
  41. int Affine2DEstimator::runRANSAC(const CvMat* m1, const CvMat* m2, CvMat* model,
  42. CvMat* mask0, double reprojThreshold,
  43. double confidence, int maxIters)
  44. {
  45. int result = 0;
  46. cv::Ptr<CvMat> mask = cvCloneMat(mask0);
  47. cv::Ptr<CvMat> models, err, tmask;
  48. cv::Ptr<CvMat> ms1, ms2;
  49. int iter, niters = maxIters;
  50. int count = m1->rows*m1->cols, maxGoodCount = 0;
  51. double min_err = 9999999;
  52. CV_Assert(CV_ARE_SIZES_EQ(m1, m2) && CV_ARE_SIZES_EQ(m1, mask));
  53. if (count < modelPoints)
  54. return false;
  55. models = cvCreateMat(modelSize.height*maxBasicSolutions, modelSize.width, CV_64FC1);
  56. err = cvCreateMat(1, count, CV_32FC1);
  57. tmask = cvCreateMat(1, count, CV_8UC1);
  58. if (count > modelPoints)
  59. {
  60. ms1 = cvCreateMat(1, modelPoints, m1->type);
  61. ms2 = cvCreateMat(1, modelPoints, m2->type);
  62. }
  63. else
  64. {
  65. niters = 1;
  66. ms1 = cvCloneMat(m1);
  67. ms2 = cvCloneMat(m2);
  68. }
  69. for (iter = 0; iter < niters || iter < 150; iter++)
  70. {
  71. int i, goodCount, nmodels;
  72. if (count > modelPoints)
  73. {
  74. bool found = getSubset(m1, m2, ms1, ms2, 300);
  75. if (!found)
  76. {
  77. if (iter == 0)
  78. return false;
  79. break;
  80. }
  81. }
  82. nmodels = runKernel(ms1, ms2, models);
  83. if (nmodels <= 0)
  84. continue;
  85. for (i = 0; i < nmodels; i++)
  86. {
  87. CvMat model_i;
  88. cvGetRows(models, &model_i, i*modelSize.height, (i + 1)*modelSize.height);
  89. goodCount = findInliers(m1, m2, &model_i, err, tmask, reprojThreshold);
  90. double _err = geterr(err, tmask);
  91. if (goodCount > MAX(maxGoodCount, modelPoints - 1) || (goodCount == MAX(maxGoodCount, modelPoints) && _err < min_err))
  92. {
  93. min_err = _err;
  94. std::swap(tmask, mask);
  95. cvCopy(&model_i, model);
  96. maxGoodCount = goodCount;
  97. niters = cvRANSACUpdateNumIters(confidence,
  98. (double)(count - goodCount) / count, modelPoints, niters);
  99. }
  100. }
  101. }
  102. if (maxGoodCount > 0)
  103. {
  104. if (mask != mask0)
  105. cvCopy(mask, mask0);
  106. result = maxGoodCount;
  107. }
  108. return result;
  109. }
  110. template<class Point > inline double distance(const Point& p1, const Point& p2){ return sqrt((p2.x - p1.x)*(p2.x - p1.x) + (p2.y - p1.y)*(p2.y - p1.y)); }
  111. //±äÐÎÂÊ
  112. double Affine2DEstimator::getMinHeight(const CvMat* m1, const CvMat* m2)
  113. {
  114. const Point2d* from = reinterpret_cast<const Point2d*>(m1->data.ptr);
  115. const Point2d* to = reinterpret_cast<const Point2d*>(m2->data.ptr);
  116. double d1[10], d2[10];
  117. int count = 0;
  118. for (int i = 0; i < 3; i++)
  119. {
  120. for (int j = i + 1; j < 3; j++)
  121. {
  122. d1[count] = ::distance(from[i], from[j]);
  123. d2[count] = ::distance(to[i], to[j]);
  124. count++;
  125. }
  126. }
  127. double p = (d1[0] + d1[1] + d1[2]) / 2.0;
  128. double s = sqrt(p*(p - d1[0])*(p - d1[1])*(p - d1[2]));
  129. double h[3] = { d1[0] < 1 ? 0 : s * 2 / d1[0], d1[1] < 1 ? 0 : s * 2 / d1[1], d1[2] < 1 ? 0 : s * 2 / d1[2] };
  130. return min(min(h[0], h[1]), h[2]);
  131. }
  132. //±äÐÎÂÊ
  133. double Affine2DEstimator::getDistortion(const CvMat* m1)
  134. {
  135. CvPoint2D64f from[] = { cvPoint2D64f(0, 0), cvPoint2D64f(10000, 0), cvPoint2D64f(0, 10000) };
  136. CvPoint2D64f to[] = {
  137. cvPoint2D64f(CV_MAT_ELEM(*m1, double, 0, 0)*from[0].x + CV_MAT_ELEM(*m1, double, 0, 1)*from[0].y + CV_MAT_ELEM(*m1, double, 0, 2), CV_MAT_ELEM(*m1, double, 1, 0)*from[0].x + CV_MAT_ELEM(*m1, double, 1, 1)*from[0].y + CV_MAT_ELEM(*m1, double, 1, 2)),
  138. cvPoint2D64f(CV_MAT_ELEM(*m1, double, 0, 0)*from[1].x + CV_MAT_ELEM(*m1, double, 0, 1)*from[1].y + CV_MAT_ELEM(*m1, double, 0, 2), CV_MAT_ELEM(*m1, double, 1, 0)*from[1].x + CV_MAT_ELEM(*m1, double, 1, 1)*from[1].y + CV_MAT_ELEM(*m1, double, 1, 2)),
  139. cvPoint2D64f(CV_MAT_ELEM(*m1, double, 0, 0)*from[2].x + CV_MAT_ELEM(*m1, double, 0, 1)*from[2].y + CV_MAT_ELEM(*m1, double, 0, 2), CV_MAT_ELEM(*m1, double, 1, 0)*from[2].x + CV_MAT_ELEM(*m1, double, 1, 1)*from[2].y + CV_MAT_ELEM(*m1, double, 1, 2))
  140. };
  141. double d1[10], d2[10];
  142. int count = 0;
  143. for (int i = 0; i < 3; i++)
  144. {
  145. for (int j = i + 1; j < 3; j++)
  146. {
  147. d1[count] = ::distance(from[i], from[j]);
  148. d2[count] = ::distance(to[i], to[j]);
  149. count++;
  150. }
  151. }
  152. double distortion[100];
  153. int count2 = 0;
  154. for (int i = 0; i < count; i++)
  155. {
  156. for (int j = 0; j < count; j++)
  157. {
  158. distortion[count2] = abs(1 - (d2[i] / d2[j]) / (d1[i] / d1[j]));
  159. count2++;
  160. }
  161. }
  162. double maxdistortion = distortion[0];
  163. for (int i = 0; i < count2; i++)
  164. {
  165. if (maxdistortion < distortion[i]){ maxdistortion = distortion[i]; }
  166. }
  167. return maxdistortion;
  168. }
  169. Mat getAffineTransform64f(const Point2d src[], const Point2d dst[])
  170. {
  171. Mat M(2, 3, CV_64F), X(6, 1, CV_64F, M.data);
  172. double a[6 * 6], b[6];
  173. Mat A(6, 6, CV_64F, a), B(6, 1, CV_64F, b);
  174. for (int i = 0; i < 3; i++)
  175. {
  176. int j = i * 12;
  177. int k = i * 12 + 6;
  178. a[j] = a[k + 3] = src[i].x;
  179. a[j + 1] = a[k + 4] = src[i].y;
  180. a[j + 2] = a[k + 5] = 1;
  181. a[j + 3] = a[j + 4] = a[j + 5] = 0;
  182. a[k] = a[k + 1] = a[k + 2] = 0;
  183. b[i * 2] = dst[i].x;
  184. b[i * 2 + 1] = dst[i].y;
  185. }
  186. solve(A, B, X);
  187. return M;
  188. }
  189. int Affine2DEstimator::runKernel(const CvMat* m1, const CvMat* m2, CvMat* model)
  190. {
  191. const Point2d* from = reinterpret_cast<const Point2d*>(m1->data.ptr);
  192. const Point2d* to = reinterpret_cast<const Point2d*>(m2->data.ptr);
  193. Mat M0 = cv::cvarrToMat(model);
  194. Mat M = getAffineTransform64f(from, to);
  195. CV_Assert(M.size() == M0.size());
  196. M.convertTo(M0, M0.type());
  197. return model != NULL ? 1 : 0;
  198. }
  199. int estimateAffine2D(InputArray _from, InputArray _to,
  200. OutputArray _out, OutputArray _inliers,
  201. double param1, double param2)
  202. {
  203. Mat from = _from.getMat(), to = _to.getMat();
  204. int count = from.checkVector(2, CV_32F);
  205. CV_Assert(count >= 0 && to.checkVector(2, CV_32F) == count);
  206. _out.create(2, 3, CV_64F);
  207. Mat out = _out.getMat();
  208. //_inliers.create(count, 1, CV_8U, -1, true);
  209. _inliers.create(1, count, CV_8U, -1, true);
  210. Mat inliers = _inliers.getMat();
  211. inliers = Scalar::all(1);
  212. Mat dFrom, dTo;
  213. from.convertTo(dFrom, CV_64F);
  214. to.convertTo(dTo, CV_64F);
  215. CvMat F2x3 = out;
  216. CvMat mask = inliers;
  217. CvMat m1 = dFrom;
  218. CvMat m2 = dTo;
  219. const double epsilon = std::numeric_limits<double>::epsilon();
  220. param1 = param1 <= 0 ? 3 : param1;
  221. param2 = (param2 < epsilon) ? 0.99 : (param2 > 1 - epsilon) ? 0.99 : param2;
  222. return Affine2DEstimator().runRANSAC(&m1, &m2, &F2x3, &mask, param1, param2);
  223. }
  224. bool Affine2DEstimator::getSubset(const CvMat* m1, const CvMat* m2,
  225. CvMat* ms1, CvMat* ms2, int maxAttempts)
  226. {
  227. cv::AutoBuffer<int> _idx(modelPoints);
  228. int* idx = _idx;
  229. int i = 0, j, k, idx_i, iters = 0;
  230. int type = CV_MAT_TYPE(m1->type), elemSize = CV_ELEM_SIZE(type);
  231. const int *m1ptr = m1->data.i, *m2ptr = m2->data.i;
  232. int *ms1ptr = ms1->data.i, *ms2ptr = ms2->data.i;
  233. int count = m1->cols*m1->rows;
  234. assert(CV_IS_MAT_CONT(m1->type & m2->type) && (elemSize % sizeof(int) == 0));
  235. elemSize /= sizeof(int);
  236. for (; iters < maxAttempts; iters++)
  237. {
  238. for (i = 0; i < modelPoints && iters < maxAttempts;)
  239. {
  240. idx[i] = idx_i = cvRandInt(&rng) % count;
  241. for (j = 0; j < i; j++)
  242. if (idx_i == idx[j])
  243. break;
  244. if (j < i)
  245. continue;
  246. for (k = 0; k < elemSize; k++)
  247. {
  248. ms1ptr[i*elemSize + k] = m1ptr[idx_i*elemSize + k];
  249. ms2ptr[i*elemSize + k] = m2ptr[idx_i*elemSize + k];
  250. }
  251. if (checkPartialSubsets && (!checkSubset(ms1, i + 1) || !checkSubset(ms2, i + 1)))
  252. {
  253. iters++;
  254. continue;
  255. }
  256. i++;
  257. }
  258. if (!checkPartialSubsets && i == modelPoints &&
  259. (!checkSubset(ms1, i) || !checkSubset(ms2, i)))
  260. continue;
  261. break;
  262. }
  263. return i == modelPoints && iters < maxAttempts;
  264. }
  265. bool Affine2DEstimator::checkSubset(const CvMat* ms1, int count)
  266. {
  267. int j, k, i, i0, i1;
  268. CvPoint2D64f* ptr = (CvPoint2D64f*)ms1->data.ptr;
  269. assert(CV_MAT_TYPE(ms1->type) == CV_64FC2);
  270. if (checkPartialSubsets)
  271. i0 = i1 = count - 1;
  272. else
  273. i0 = 0, i1 = count - 1;
  274. for (i = i0; i <= i1; i++)
  275. {
  276. // check that the i-th selected point does not belong
  277. // to a line connecting some previously selected points
  278. for (j = 0; j < i; j++)
  279. {
  280. double dx1 = ptr[j].x - ptr[i].x;
  281. double dy1 = ptr[j].y - ptr[i].y;
  282. for (k = 0; k < j; k++)
  283. {
  284. double dx2 = ptr[k].x - ptr[i].x;
  285. double dy2 = ptr[k].y - ptr[i].y;
  286. if (fabs(dx2*dy1 - dy2*dx1) <= FLT_EPSILON*(fabs(dx1) + fabs(dy1) + fabs(dx2) + fabs(dy2)))
  287. break;
  288. }
  289. if (k < j)
  290. break;
  291. }
  292. if (j < i)
  293. break;
  294. }
  295. return i >= i1;
  296. }
  297. Affine2DEstimator::Affine2DEstimator() : modelPoints(3), modelSize(cvSize(3, 2)), maxBasicSolutions(1)
  298. {
  299. checkPartialSubsets = true;
  300. rng = cvRNG(-1);
  301. }