opencv features2d对象识别
在生活中,经常会遇到这样的一种情况,上班要出门的时候,突然找不到一件东西了,比如钥匙、手机或者手表等。这个时候一般在房间翻一遍各个角落来寻找不见的物品,最后突然一拍大脑,想到在某一个地方,在整个过程中有时候是很着急的,并且越着急越找不到,真是令人沮丧。但是,如果一个简单的计算机算法可以在几毫秒内就找到你要找的物品,你的感受如何?是不是很惊奇!这就是对象检测算法(object detection)的力量。虽然上述举的生活例子只是一个很简单的例子,但对象检测的应用范围很广,跨越多个不同的行业,从全天候监控到智能城市的实时车辆检测等。简而言之,物体检测是强大的深度学习算法中的一个分支。
代码:
const Ptr<AKAZE> &detetor = AKAZE::create();
vector<KeyPoint> oneKeyPoint;
vector<KeyPoint> twoKeyPoint;
Mat oneDes, twoDes;
//角点查找和特征向量计算描述
detetor->detectAndCompute(oneMat, Mat(), oneKeyPoint, oneDes);
detetor->detectAndCompute(twoMat, Mat(), twoKeyPoint, twoDes);
vector<DMatch> matches;
//匹配描述向量
const Ptr<BFMatcher> &bfm = BFMatcher::create();
bfm->match(oneDes, twoDes, matches);
//查找最大值最小值
double minVal=100, maxVal = 0;
for (int i = 0; i < matches.size(); ++i) {
if (matches[i].distance>maxVal)
maxVal=matches[i].distance;
if (matches[i].distance<minVal)
minVal=matches[i].distance;
}
//阈值筛选
vector<DMatch> goods;
for (int i = 0; i < oneDes.rows; ++i) {
if (matches[i].distance<8*minVal){
goods.push_back(matches[i]);
}
}
//绘制焦点匹配
drawMatches(oneMat, oneKeyPoint, twoMat, twoKeyPoint, goods, dstMat);
vector<Point2f> obj;
vector<Point2f> scene;
for (int i = 0; i < goods.size(); ++i) {
obj.push_back(oneKeyPoint[goods[i].queryIdx].pt);
scene.push_back(twoKeyPoint[goods[i].trainIdx].pt);
}
//透视变换
const Mat &H = getPerspectiveTransform(obj, scene);
vector<Point2f> obj_corners(4);
vector<Point2f> scene_corners(4);
obj_corners[0]= Point2f(0,0);
obj_corners[1]= Point2f(oneMat.cols,0);
obj_corners[2]= Point2f(oneMat.cols,oneMat.rows);
obj_corners[3]= Point2f(0,oneMat.rows);
perspectiveTransform(obj_corners, scene_corners, H);
//画出匹配区域
Point2f offset(oneMat.cols, 0);
line(dstMat, scene_corners[0]+offset, scene_corners[1]+offset,Scalar(0,255,0),4);
line(dstMat, scene_corners[1]+offset, scene_corners[2]+offset,Scalar(0,255,0),4);
line(dstMat, scene_corners[2]+offset, scene_corners[3]+offset,Scalar(0,255,0),4);
line(dstMat, scene_corners[3]+offset, scene_corners[0]+offset,Scalar(0,255,0),4);
LOGI("jason min max %f %f", minVal , maxVal);