- まずエッジ点の抽出は主にVisionProのCogCaliperToolツールの原理を学びます。
- その後、エッジ点セットを取得した後、RANSAC アルゴリズムを使用して外れ値を除外します。RANSAC のアルゴリズム原理は、RANSAC アルゴリズム (RANSAC 直線フィッティング C++ および Python バージョンを使用)に若干の変更を加えたものであり、反復回数は次の式に従って計算されます。k = log ( 1 − p ) log ( 1 − wn ) k=\ frac{log(1-p)}{log(1-w^n)}k=l o g ( 1 − wn )l o g ( 1 − p )。
void CCaliperGraphics::RansacLineFiler(const vector<Point2d>& points,vector<Point2d>&vpdExceptPoints, double sigma)
{
unsigned int n = points.size();
if (n < 2)
{
return;
}
RNG random;
double bestScore = -1.;
vector<Point2d>vpdTemp;
int iterations = log(1 - 0.99) / (log(1 - (1.00 / n)))*10;
for (int k = 0; k < iterations; k++)
{
int i1 = 0, i2 = 0;
while (i1 == i2)
{
i1 = random(n);
i2 = random(n);
}
const cv::Point2d& p1 = points[i1];
const cv::Point2d& p2 = points[i2];
Point2d vectorP21 = p2 - p1;
vectorP21 *= 1. / norm(vectorP21);
double score = 0;
vpdTemp.clear();
for (int i = 0; i < n; i++)
{
Point2d vectorPi1 = points[i] - p1;
double d = vectorPi1.y * vectorP21.x - vectorPi1.x * vectorP21.y;//calculate the cos�� of the two vectors.
if (fabs(d) < sigma)
{
score += 1;
}
else
{
vpdTemp.push_back(points[i]);
}
}
if (score > bestScore)
{
bestScore = score;
vpdExceptPoints = vpdTemp;
}
}
}
- 最後に、fitLine を使用して直線フィッティングを実行します。
最終効果:
ImageWatch で画像を拡大し、
opencv のトラックバーとマウス イベントを使用して、キャリパーを簡単にドラッグして編集できます。キャリパー
の実装でさらに面倒なのはサンプリング方向です。私の定義は次の図に示すとおりです。線分と X 軸の間の角度を次のように計算します。ベクトルの角度公式 また逆に線分の中心と方向と長さがあれば線分の始点と終点を計算することができます。
static double GetAngleVecWithX(Point2d p1,Point2d p2)
{
if (p1 == p2)
{
return -1;
}
Point2d vector = p2 - p1;
if (vector.x == 0)
{
if (vector.y > 0)
{
return 90;
}
else
{
return -90;
}
}
double angle = to_degree(acos(pow(vector.x, 2) / (vector.x * sqrt(pow(vector.x, 2) + pow(vector.y, 2)))));
if (p1.y > p2.y)
{
angle = -angle;
}
return angle;
}
また、組み込みのdrawArrowはあまり役に立たないと思うので、RotateRectを使用して書き直しました。十字架を描くのも同様の原理です。
static void DrawArrow(Mat& inputMat, Point2d p1, Point2d p2, int dSize, Scalar color, int nThickness = 1)
{
if (inputMat.empty())
{
return;
}
double dK = ((double)p2.y - (double)p1.y) / ((double)p2.x - (double)p1.x);
double dAngle = atan(dK) * 180 / PI;
line(inputMat, p1, p2, color, nThickness, LINE_AA);
RotatedRect rotateRect(p2, Size(dSize, dSize * 0.5), dAngle);
Point2f rectPoints[4];
rotateRect.points(rectPoints);
if ((dAngle >= 0 && p1.x <= p2.x) || (dAngle < 0 && p1.x <= p2.x))
{
line(inputMat, p2, rectPoints[0], color, nThickness, LINE_AA);
line(inputMat, p2, rectPoints[1], color, nThickness, LINE_AA);
}
else
{
line(inputMat, p2, rectPoints[2], color, nThickness, LINE_AA);
line(inputMat, p2, rectPoints[3], color, nThickness, LINE_AA);
}
}
opencv に基づいてソース コードを検索するキャリパー ライン
キャリパーで円を見つけるのにも同じ原理が使用され、その効果は円を見つけるための openCV キャリパーに基づいています。
更新: WPF と Opencvsharp を使用してキャリパー ライン検索の UI を実現し、表示コントロールは WPF によって実現される Halcon の学習のウィンドウです。