//模板文件名
private static String [] template_name={ "right1.jpg","left1.jpg","direct1.jpg","undirect1.jpg","unthrough1.jpg","return1.jpg","right2.jpg","left2.jpg","direct2.jpg","undirect2.jpg","unthrough2.jpg","return2.jpg","right3.jpg"};
private static double [] template_int=new double[template_name.length];
public static String Signal_re(Mat mat){
// 创建ORB特征检测器
ORB orb = ORB.create();
Mat gray=new Mat();
Imgproc.cvtColor(mat, gray, Imgproc.COLOR_BGR2GRAY);
// 提取图像1和图像2的ORB特征点和描述符
MatOfKeyPoint keypoints1 = new MatOfKeyPoint();
MatOfKeyPoint keypoints2 = new MatOfKeyPoint();
Mat descriptors1 = new Mat();
Mat descriptors2 = new Mat();
orb.detectAndCompute(gray, new Mat(), keypoints1, descriptors1);
Mat templat_mat = new Mat();
Mat templat_gray = new Mat();
// 创建特征点匹配器
MatOfDMatch matches = new MatOfDMatch();
DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
for (int i = 0; i < template_name.length; i++) {
templat_mat = Activity_test.read_pic(false, template_name[i], 6);
Imgproc.cvtColor(templat_mat, templat_gray, Imgproc.COLOR_BGR2GRAY);
orb.detectAndCompute(templat_gray, new Mat(), keypoints2, descriptors2);
matcher.match(descriptors1, descriptors2, matches);
// 计算匹配距离的分布
List<DMatch> matchesList = matches.toList();
double maxDist = 0;
double minDist = 20;
// 根据匹配距离的分布,设定匹配阈值
double threshold = 2 * minDist;
// 筛选匹配点
List<DMatch> goodMatches = new ArrayList<DMatch>();
for (int k = 0; k < matchesList.size(); k++) {
if (matchesList.get(k).distance < threshold) {
goodMatches.add(matchesList.get(k));
}
}
template_int[i]=(float)goodMatches.size()/(float)matchesList.size();
}
double max=template_int[0];
int flag_index=0;
for (int i = 1; i <template_int.length ; i++) {
if(template_int[i]>max){
max=template_int[i];
flag_index=i;
}
}
//匹配度,可更改调节阈值,返回匹配到的文件名
if(template_int[flag_index]>0.1){
Log.d("Signal",template_name[flag_index]);
return template_name[flag_index];
}
return null;
OpenCV Android 模板匹配
该代码段使用ORB特征检测器对图像进行处理,通过BRUTEFORCE_HAMMING匹配算法计算图像间的相似度。通过对匹配距离的分析设置阈值,筛选出最佳匹配,从而确定最相似的模板文件名。
摘要由CSDN通过智能技术生成