Opencv4Android getPerspectiveTransform错误

Opencv4Android getPerspectiveTransform error

我想使用 getPerspectiveTransform 函数,但它只接受 Mat 作为参数并且我在数组中有坐标数据。所以我将它们转换为点,然后按如下方式转换为 Mat:

List<Point> l = new ArrayList<Point>();
for (int i = 0; i < pts_1.length; i++) {
    Point pt = new Point(pts_1[0][i], pts_1[1][i]);
    l.add(i,pt);
}
Mat mat1 = Converters.vector_Point2f_to_Mat(l);
for (int i = 0; i < pts_2.length; i++) {
    Point pt = new Point(pts_2[0][i], pts_2[1][i]);
    l.add(i,pt);
    }
Mat mat2 = Converters.vector_Point2f_to_Mat(l);
Mat perspectiveTransform = Imgproc.getPerspectiveTransform(mat1,mat2);

但是当我 运行 我的应用程序时,它给我错误 'Something went wrong',并且在 logcat 中我收到以下错误:

E/cv::error(): OpenCV Error: Assertion failed (src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4) in cv::Mat cv::getPerspectiveTransform(cv::InputArray, cv::InputArray), file /build/master_pack-android/opencv/modules/imgproc/src/imgwarp.cpp, line 6748
E/org.opencv.imgproc: imgproc::getPerspectiveTransform_10() caught cv::Exception: /build/master_pack-android/opencv/modules/imgproc/src/imgwarp.cpp:6748: error: (-215) src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4 in function cv::Mat cv::getPerspectiveTransform(cv::InputArray, cv::InputArray)

我是 OpenCV4Android 的新手,所以我不明白为什么会这样。如何解决?还有其他更好的方法吗?

感谢帮助!

注意:我知道这里遵循类似的程序:Can't get OpenCV's warpPerspective to work on Android 但他没有收到此错误,所以我将其发布在这里。

正如在关于 OP post 的评论讨论中提到的(全部归功于他们),问题出在列表 l:

List<Point> l = new ArrayList<Point>();
for (int i = 0; i < pts_1.length; i++) {
    Point pt = new Point(pts_1[0][i], pts_1[1][i]);
    l.add(i,pt);
}
Mat mat1 = Converters.vector_Point2f_to_Mat(l);

如果我们看一下 List<Point> l 的内容:

for (Point pt : l)
    System.out.println("(" + pt.x + ", " + p.ty + ")");

(x0, y0)
(x1, y1)
(x2, y2)
(x3, y3)

并移动到下一个矩阵:

for (int i = 0; i < pts_2.length; i++) {
    Point pt = new Point(pts_2[0][i], pts_2[1][i]);
    l.add(i,pt);
    }
Mat mat2 = Converters.vector_Point2f_to_Mat(l);

再看一下List<Point> l的内容:

for (Point pt : l)
    System.out.println("(" + pt.x + ", " + p.ty + ")");

(x4, y4)
(x5, y5)
(x6, y6)
(x7, y7)
(x0, y0)
(x1, y1)
(x2, y2)
(x3, y3)

所以这是罪魁祸首;你的第二个矩阵将有 8 个点。

来自Java docs for ArrayList

Parameters: index - index at which the specified element is to be inserted

使用 l.add 插入 而不会覆盖旧列表。所以解决方案是为每个转换矩阵制作一个新列表。