【发布时间】:2021-08-24 13:41:30
【问题描述】:
1. sort(arr1.begin(), arr1.end(), [](Point2f lhs, Point2f rhs) { return lhs.x<rhs.x; } );
2. sort(arr1.begin(), arr1.begin()+2, [](Point2f lhs, Point2f rhs) { return lhs.y<rhs.y; });
3. sort(arr1.begin()+2, arr1.end(), [](Point2f lhs, Point2f rhs) { return lhs.y<rhs.y; });
我正在尝试对一组点 (top-left --> bottom-left --> top-right --> bottom-right) 进行排序。我想将以上内容转换为 C#,但我不确定如何完成以上内容。到目前为止,我已经完成了以下操作:
var sortedArr1 = arr1.OrderBy(r => r.X).ThenBy(r=>r.Y).ToList();
我认为完成了语句 1 和 2,但没有解决最后一个语句。
[编辑] 基于下面的 cmets,我从源代码中添加了一个 sn-p。
public List<Point2d> DetectCorners(Mat src)
{
var lines = src.HoughLines(1, Cv2.PI / 180, 50, 0, 0);
Mat labels = new Mat();
Mat centers = new Mat();
List<Point2f> data = new List<Point2f>();
for (uint i = 0; i < lines.Length; i++)
{
float rho = lines[i].Rho;
float theta = lines[i].Theta;
float x = rho * (float)Math.Cos(theta);
float y = rho * (float)Math.Sin(theta);
data.Add(new Point2f(x, y));
}
Cv2.Kmeans(InputArray.Create(data), 4, labels,
new TermCriteria(CriteriaType.Eps & CriteriaType.Count, 10, 1.0), 5, KMeansFlags.PpCenters, centers);
List<Point2f> fourPoints = new List<Point2f>();
List<Point2f> xyPoints = new List<Point2f>();
for (int i = 0; i < 4; i++)
{
float x = centers.At<float>(i, 0);
float y = centers.At<float>(i, 1);
float rho = (float)Math.Sqrt(x * x + y * y);
float theta = (float)Math.Atan2(y, x);
xyPoints.Add(new Point2f(x, y));
fourPoints.Add(new Point2f(rho, theta));
}
var sortedXyPoints = xyPoints.OrderBy(r => Math.Abs(r.Y / r.X)).ToArray();
List<Point2d> ans = new List<Point2d>();
for (uint i = 0; i < 2; i++)
{
float x0 = sortedXyPoints[i].X;
float y0 = sortedXyPoints[i].Y;
for (uint j = 2; j < 4; j++)
{
float x1 = sortedXyPoints[j].X;
float y1 = sortedXyPoints[j].Y;
float x = (y0 * (x1 * x1 + y1 * y1) - y1 * (x0 * x0 + y0 * y0)) / (y0 * x1 - x0 * y1);
float y = (x0 * (x1 * x1 + y1 * y1) - x1 * (x0 * x0 + y0 * y0)) / (y1 * x0 - x1 * y0);
ans.Add(new Point2d(x, y));
}
}
// order of points (top-left, bottom-left, top-right, bottom-right)
var sortedAns = ans.OrderBy(r => r.X).ThenBy(r=>r.Y).ToArray();
//TODO: convert sort(arr1.begin()+2, arr1.end(), [](Point2f lhs, Point2f rhs) { return lhs.y<rhs.y; }); to c#
return new List<Point2d>(sortedAns);
}
【问题讨论】:
-
“左上、左下、右上、右下”是什么意思?
-
C++ 代码首先按 x 坐标对整个数组进行排序,然后按 y 坐标对前 2 个元素进行排序,然后按 y 坐标对所有其他元素进行排序。你确定它做你想做的事吗?在一般情况下,这似乎很奇怪。
-
你测试过这段代码吗?如果没有,您能否提供一个 C# minimal reproducible example。这个问题不需要
c++标签。 -
旁注:这个 C++ 代码看起来很可疑(算法)。这应该怎么做?
-
arr1的本质是什么?我们对这个数组了解多少?它是否总是有 4 个元素,其中 2 个具有一个 X 值,2 个具有另一个值?