[英]Sorting Point[] left-right and top-down
我在Android中使用OpenCV從輪廓應用4點變換。 我使用Imgproc.findContours
查找輪廓。 我找到輪廓的代碼:
public MatOfPoint2f FindPaper(Mat edged) {
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(edged, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
if (contours.size() > 0) {
Collections.sort(contours, new ContourComparator()); // compare by area
for (MatOfPoint cnt : contours) {
MatOfPoint2f matrix = new MatOfPoint2f();
MatOfPoint2f approxMatrix = new MatOfPoint2f();
cnt.convertTo(matrix, CvType.CV_32FC2);
double peri = Imgproc.arcLength(matrix, true);
Imgproc.approxPolyDP(matrix, approxMatrix, 0.02 * peri, true);
if (approxMatrix.size().height == 4){
return approxMatrix;
}
}
}
return null;
}
以下是我的4點轉換代碼:
public Mat FourPointTransform(Mat input, MatOfPoint2f cutMat){
Point[] canonicalPoints = new Point[4];
canonicalPoints[0] = new Point(input.width(), 0);
canonicalPoints[1] = new Point(0,0);
canonicalPoints[2] = new Point(0, input.height());
canonicalPoints[3] = new Point(input.width(), input.height());
MatOfPoint2f canonicalMarker = new MatOfPoint2f();
canonicalMarker.fromArray(canonicalPoints);
// how to sort these points Left-Right to Top-Down?
//Point[] cutPoints = SortPoint(cutMat.toArray());
MatOfPoint2f marker = new MatOfPoint2f(cutMat.toArray());
Mat transform = Imgproc.getPerspectiveTransform(marker, canonicalMarker);
Mat dest = new Mat(input.rows(), input.cols(), input.type());
Imgproc.warpPerspective(input, dest, transform, dest.size());
return dest;
}
有時, FourPointTansform
生成的Mat
被翻轉或旋轉。 如何對點進行左右排序和自上而下排序?
經過數天的反復試驗,這是對我的陣列的正確排序。
public static IEnumerable<PointF> SortPoints(IEnumerable<PointF> input)
{
var sorted = new PointF[4];
var listedInput = input.ToList();
// top-left --> min(x+y)
sorted[0] = listedInput.GroupBy(x => x.X + x.Y).OrderBy(x => x.Key).First().First();
// bottom-right --> max(x+y)
sorted[2] = listedInput.GroupBy(x => x.X + x.Y).OrderByDescending(x => x.Key).First().First();
// top-right --> min(x-y)
sorted[1] = listedInput.GroupBy(x => x.X - x.Y).OrderBy(x => x.Key).First().First();
// bottom-left --> max(x-y)
sorted[3] = listedInput.GroupBy(x => x.X - x.Y).OrderByDescending(x => x.Key).First().First();
return sorted;
}
上面的代碼在C#中,並使用EmguCV。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.