在Java中向MatOfPoint变量添加值

4

我正在尝试将一个double[][]转换为 OpenCVMatOfPointpointsOrdered 是一个double[4][2],其中包含四个点的坐标。

我已经尝试了以下方法:

MatOfPoint sourceMat =  new MatOfPoint();
for (int idx = 0; idx < 4; idx++) {
    (sourceMat.get(idx, 0))[0] = pointsOrdered[idx][0];
    (sourceMat.get(idx, 0))[1] = pointsOrdered[idx][1];
}

但是sourceMat的值保持不变。我正在尝试逐个添加值,因为我没有找到其他选项。

我该怎么办?是否有一种简单的方法可以访问和修改MatOfPoint变量的值?


MatOfPoint是什么数据类型,它属于OpenCV的哪种类型? - Bahramdun Adil
是的,我忘了说了,抱歉。我已经更新了问题。 - andraga91
为什么您要使用MatOfPoint?您没有使用Point类型的输入用于MatOfPoint吗? - Ömer Erden
我需要进行透视变换。我已经看到Imgproc.getPerspectiveTransform需要一个包含空间有序点的MatOfPoint变量(我已将其存储在double [4] [2]中)。 - andraga91
如果要将x,y存储在MatOfPoint中,则您输入值的类型必须为Point,请检查我的答案。 - Ömer Erden
2个回答

2

org.opencv.core.MatOfPoint 期望 org.opencv.core.Point 对象,但它存储的是 Point 对象的属性值 (x,y),而不是 Point 对象本身。

如果您将 double[][] pointsOrdered 数组转换为 ArrayList<Point>

ArrayList<Point> pointsOrdered = new ArrayList<Point>();
pointsOrdered.add(new Point(xVal, yVal));
...

那么你可以从这个 ArrayList<Point> 创建一个 MatOfPoint

MatOfPoint sourceMat = new MatOfPoint();
sourceMat.fromList(pointsOrdered);
//your sourceMat is Ready.

0
这是一个过度复杂的示例答案,展示了可以结合使用列表/数组/数组列表(选择您喜欢的)以及实际上错误的问题。 "Mat get"方法和"Mat put"方法被混淆 - 在使用中颠倒了。
MatOfPoint sourceMat=new MatOfPoint();

sourceMat.fromArray( // a recommended way to initialize at compile time if you know the values
                new Point(151., 249.),
                new Point(105., 272.),
                new Point(102., 318.),
                new Point(138., 337.));

// A way to change existing data or put new data if need be if you set the size of the MatOfPoints first
double[] corner=new double[(int)(sourceMat.channels())];// 2 channels for a point

for (int idx = 0; idx<sourceMat.rows(); idx++) {
     System.out.println((corner[0]=sourceMat.get(idx, 0)[0]) + ", " + (corner[1]=sourceMat.get(idx, 0)[1]));
     corner[0]+=12.; // show some change can be made to existing point.x
     corner[1]+=8.; // show some change can be made to existing point.y
     sourceMat.put(idx, 0, corner);
     System.out.println((corner[0]=(float)sourceMat.get(idx, 0)[0]) + ", " + (corner[1]=(float)sourceMat.get(idx, 0)[1]));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接