How to get similarity value between two different images by using OpenCV in iOS

asked 2020-04-19 05:31:32 -0600

Hi, everyone, I'm new to this library. I’m using OpenCV 4.3.0 in iOS. I’m confusing how to get similarity value between two different images. I got a base Flann matcher, match points, good match points now. If I just straightly use goodMatches.size()divided by matches.size(). I’m afraid that result is not exactly accurate. Any help will be appreciated.

+ (double)orbmatchCompareImage:(UIImage *)image targetImage:(UIImage *)targetImage {
    Mat imageMat;
    UIImageToMat(image, imageMat);
    Mat targetImageMat;
    UIImageToMat(targetImage, targetImageMat);

    if (imageMat.empty() || targetImageMat.empty()) {
        return 0;
    }
    Mat imageGreyMat;
    cvtColor(imageMat, imageGreyMat, COLOR_BGR2GRAY);
    Mat targetImageGreyMat;
    cvtColor(targetImageMat, targetImageGreyMat, COLOR_BGR2GRAY);


    vector<KeyPoint> imageCat, targetImageCat;
    auto orbDetector = ORB::create(1000);
    Mat imageDescriptor, targetImagegDescriptor;

    orbDetector -> detectAndCompute(imageGreyMat, Mat(), imageCat, imageDescriptor);
    orbDetector -> detectAndCompute(targetImageGreyMat, Mat(), targetImageCat, targetImagegDescriptor);


    flann::Index flannIndex(imageDescriptor, flann::LshIndexParams(12, 20, 2), cvflann::FLANN_DIST_HAMMING);
    vector<DMatch> goodMatches;

    Mat matchIndex(targetImagegDescriptor.rows, 2, CV_32SC1), matchDistance(targetImagegDescriptor.rows, 2, CV_32FC1);

    if (!(targetImagegDescriptor.isContinuous() && matchIndex.isContinuous() && matchDistance.isContinuous())) {
        return 0;
    }
    flannIndex.knnSearch(targetImagegDescriptor, matchIndex, matchDistance, 2);
    // Lowe's algorithm, get good match points
    for (int i = 0; i < matchDistance.rows; i++)
    {
        if (matchDistance.at<float>(i, 0) < 0.8 * matchDistance.at<float>(i, 1))
        {
            DMatch dmatches(i, matchIndex.at<int>(i, 0), matchDistance.at<float>(i, 0));
            goodMatches.push_back(dmatches);
        }
    }
    // How to get correct similarity value?
    // printf("similary: %f\n", double(goodMatches.size()) / double(matchDistance.rows));
    // printf("matchDistance rows: %d\ngoodMatches size: %lu\n", matchDistance.rows, goodMatches.size());
    // double similary;
    // similary = double(goodMatches.size()) / double(matchDistance.rows);
    // return similary;
}
edit retag flag offensive close merge delete