OpenCV透视变换函数异常。

6

如何使用perspectiveTransform函数?

当运行我的代码时,会产生以下异常:

OpenCV错误:在透视变换中断言失败(scn + 1 == m.cols && (depth == CV_32F || depth == CV_64F)),文件 /Users/donbe/Documents/opencv/opencv/modules/core/src/matmul.cpp, 第1916行

谁能帮助我?

我的代码如下:

Point2f srcTri[4];
Point2f dstTri[4];

Mat warp_mat;
Mat src;

/// Load the image
src = imread( argv[1], 1 );

srcTri[0] = Point2f(0,0);
srcTri[1] = Point2f(src.cols,0);
srcTri[2] = Point2f(src.cols,src.rows);
srcTri[3] = Point2f(0,src.rows);

dstTri[0] = Point2f(0,0);
dstTri[1] = Point2f(src.cols/2,0);
dstTri[2] = Point2f(src.cols/2,src.rows);
dstTri[3] = Point2f(0,src.rows);


warp_mat =  getPerspectiveTransform(srcTri, dstTri);

Mat warp_dst(src.size(), src.type());    

//There will produce a exception.
perspectiveTransform(src, warp_dst, warp_mat);

namedWindow( "Warp", CV_WINDOW_AUTOSIZE );
imshow( "Warp", warp_dst );

waitKey(0);
return 0;
3个回答

6
你是否检查过源图像以确保它符合要求?
void perspectiveTransform(InputArray src, OutputArray dst, InputArray mtx)

Parameters: 

src – Source two-channel or three-channel floating-point array. Each element is a 2D/3D vector to be transformed.
dst – Destination array of the same size and type as src .
mtx – 3x3 or 4x4 floating-point transformation matrix.

注意:
该函数可以转换一个稀疏的二维或三维向量集。如果您想使用透视变换来转换图像,请使用warpPerspective()。
有关更多详细信息,请查阅文档:http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=perspectivetransform#cv2.perspectiveTransform 希望这能帮到您。

5
我在Python中遇到了同样的问题,得出结论是需要针对一个3x3矩阵提供mxnx2的输入和输出数组,而我只有一个nx2的数据x。因此,这个方法可以解决问题:y=cv2.perspectiveTransform(x[np.newaxis], H)[0] - Ben
@Ben的评论应该在这里作为答案,因为它正是我的问题所在,我只有在运行来自https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_feature2d/py_feature_homography/py_feature_homography.html?highlight=perspectivetransform#code的示例代码后才发现:h,w = img1.shapepts = np.float32([[0,0],[0,h-1],[w-1,h-1],[w-1,0]]).reshape(-1,1,2)dst = cv2.perspectiveTransform(pts,M) - jugi

1
在我的情况下,我也遇到了同样的错误,问题出在输入数组mtx的类型上。将CvMat *obj的类型从CV_8UC1更改为CV_32FC1就解决了!

1
当我在Python中遇到这个问题时,我发现是因为输入应该是三维的:
>>> cv2.perspectiveTransform(np.float32([[1,1]]), np.float32([[1,0,0],[0,1,0],[0,0,1]]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.5.1) /tmp/pip-req-build-1syr35c1/opencv/modules/core/src/matmul.dispatch.cpp:531: error: (-215:Assertion failed) scn + 1 == m.cols in function 'perspectiveTransform'

>>> cv2.perspectiveTransform(np.float32([[[1,1]]]), np.float32([[1,0,0],[0,1,0],[0,0,1]]))
array([[[1., 1.]]], dtype=float32)

这段文字在文档中表达得非常糟糕,只简单地说明了“src:输入二通道或三通道浮点数组;每个元素是要进行变换的2D / 3D向量”,因此可能会引起混淆。
为了使函数按预期行为运行 - 即对点数组进行操作,请按如下方式调用它:
dst = cv2.perspectiveTransform(src[np.newaxis], m)[0]

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