opencv_C++ 平面对象识别与透视变换

文章目录

        • 一、需要用到的函数
        • 二、代码示例
        • 三、结果展示

一、需要用到的函数

需要用到两个函数:
findHomography 发现两个平面的透视变换,生成变换矩阵
perspectiveTransform 透视变换

还用到一个对象,DMatch 对象参数:
distance:每一个mathes 的距离;
trainIdx: 这个属性为我们提供了样本图像描述符列表中的描述符索引就是obj in scene图片的可以points。drawMatches()函数中的img2。
queryIdx: keypoints 是哪个的,这个属性为我们提供测试图像描述符列表中的描述符索引。就是obj 的图片的keypoints。drawMatches()函数中的img1。
imgIdx: 当样本是多张图像的话有用。

二、代码示例

#include 
#include 
using namespace cv;
using namespace std;
using namespace cv::xfeatures2d;

int main()
{
	Mat srcImage = imread("curry_dlt.jpg");
	Mat dstImage = imread("curry1.jpg");

	// surf 特征提取
	int minHessian = 450;
	Ptr detector = SURF::create(minHessian);
	vector keypoints_src;
	vector keypoints_dst;
	Mat descriptor_src, descriptor_dst;
	detector->detectAndCompute(srcImage, Mat(), keypoints_src, descriptor_src);
	detector->detectAndCompute(dstImage, Mat(), keypoints_dst, descriptor_dst);

	// matching
	FlannBasedMatcher matcher;
	vector matches;
	matcher.match(descriptor_dst, descriptor_src, matches);

	// find good matched points
	double minDist = 0, maxDist = 0;
	for (size_t i = 0; i < matches.size(); i++)
	{
		double dist = matches[i].distance;
		if (dist > maxDist)
			maxDist = dist;
		if (dist < minDist)
			minDist = dist;
	}

	vector goodMatches;
	for (size_t i = 0; i < matches.size(); i++)
	{
		double dist = matches[i].distance;
		if (dist < max(3 * minDist, 0.02))
		{
			goodMatches.push_back(matches[i]);
		}
	}

	Mat matchesImage;
	drawMatches(dstImage, keypoints_dst, srcImage, keypoints_src, goodMatches, matchesImage, Scalar::all(-1), \
		Scalar::all(-1), vector(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);

	//imshow("matchesImage", matchesImage);

	vector obj;
	vector objInScene;
	for (size_t t = 0; t < goodMatches.size(); t++)
	{
		obj.push_back(keypoints_dst[goodMatches[t].queryIdx].pt);
		objInScene.push_back(keypoints_src[goodMatches[t].trainIdx].pt);
	}
	Mat H = findHomography(obj, objInScene, RANSAC);

	vector obj_corners(4);
	vector scene_corners(4);
	// img1 图像的四角坐标
	obj_corners[0] = Point(0, 0);
	obj_corners[1] = Point(dstImage.cols, 0);
	obj_corners[2] = Point(dstImage.cols, dstImage.rows);
	obj_corners[3] = Point(0, dstImage.rows);
	
	perspectiveTransform(obj_corners, scene_corners, H);

	// draw line
	line(matchesImage, scene_corners[0] + Point2f(dstImage.cols, 0), \
		scene_corners[1] + Point2f(dstImage.cols, 0), Scalar(0, 0, 255), 2, 8, 0);
	line(matchesImage, scene_corners[1] + Point2f(dstImage.cols, 0), \
		scene_corners[2] + Point2f(dstImage.cols, 0), Scalar(0, 0, 255), 2, 8, 0);
	line(matchesImage, scene_corners[2] + Point2f(dstImage.cols, 0), \
		scene_corners[3] + Point2f(dstImage.cols, 0), Scalar(0, 0, 255), 2, 8, 0);
	line(matchesImage, scene_corners[3] + Point2f(dstImage.cols, 0), \
		scene_corners[0] + Point2f(dstImage.cols, 0), Scalar(0, 0, 255), 2, 8, 0);

	imshow("平面对象识别", matchesImage);

	waitKey(0);
	return 0;
}

三、结果展示

opencv_C++ 平面对象识别与透视变换_第1张图片

你可能感兴趣的:(机器视觉,【OpenCV】整理记录)