据我所知,OpenCV使用RANSAC是为了解决这个问题。findHomography
并返回一些有用的参数,如 homograph_mask
.
但是,如果我只想估计二维变换,也就是Affine Matrix,是否有办法使用同样的方法,即 findHomography
使用RANSAC并返回该掩码?
你可以直接使用 estimateAffinePartial2D 。https:/docs.opencv.org4.0.0d9d0cgroup__calib3d.html#gad767faff73e9cbd8b9d92b955b50062d。
cv::Mat cv::estimateAffinePartial2D (
InputArray from,
InputArray to,
OutputArray inliers = noArray(),
int method = RANSAC,
double ransacReprojThreshold = 3,
size_t maxIters = 2000,
double confidence = 0.99,
size_t refineIters = 10
)
比如:
src_pts = np.float32([pic1.key_points[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([pic2.key_points[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
# Find the transformation between points, standard RANSAC
transformation_matrix, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
# Compute a rigid transformation (without depth, only scale + rotation + translation) and RANSAC
transformation_rigid_matrix, rigid_mask = cv2.estimateAffinePartial2D(src_pts, dst_pts)
估算刚性变形 内部确实使用了RANSAC,尽管目前参数是固定的--见这里的代码--。https:/github.comopencvopencvbmastermodulesvideosrclkpyramid.cpp。
cv::Mat cv::estimateRigidTransform( InputArray src1, InputArray src2, bool fullAffine )
{
const int RANSAC_MAX_ITERS = 500;
const int RANSAC_SIZE0 = 3;
const double RANSAC_GOOD_RATIO = 0.5;
// ...
// RANSAC stuff:
// 1. find the consensus
for( k = 0; k < RANSAC_MAX_ITERS; k++ )
{
int idx[RANSAC_SIZE0];
Point2f a[RANSAC_SIZE0];
Point2f b[RANSAC_SIZE0];
// choose random 3 non-complanar points from A & B
for( i = 0; i < RANSAC_SIZE0; i++ )
{
for( k1 = 0; k1 < RANSAC_MAX_ITERS; k1++ )
{