删除 OpenCV 中的匹配项(关键点和描述符)

Delete matches in OpenCV (Keypoints and descriptors)

我想根据两个火车图像检查场景图像。 为此,我检测了两个训练图像的特征并计算了描述符。 在对场景图像进行检测、计算和匹配之前,我会删除train1和train2的所有匹配项。因为这些匹配不利于场景图像与train1和train2的匹配。

因此,我将 train1 与 train2 进行匹配,并获得与 trainIdx 和 queryIdx 匹配的向量。但是如何删除train1和train2的keypoints-vector和描述符矩阵中的这些匹配项呢?

此致, dwi

好的,就像 Micka 所建议的那样,我遍历所有关键点和描述符并将它们添加到一个新的 vector/matrix 中,除了匹配项。 无法将它们标记为不必要。

我会像下面那样做:

std::vector<cv::KeyPoint> keypoints[2];
cv::Mat descriptor[2];
std::vector< cv::DMatch > matches;

/* 
      Write code to generate the keypoints, descriptors and matches here...
      keypoint[0] -> Train Image 1 keypoints
      keypoint[1] -> Train Image 2 keypoints
      descriptor[0] -> Train Image 1 descriptors
      descriptor[1] -> Train Image 2 descriptors
      matches -> matched between train image 1 and 2

*/

// Logic to keep unmatched keypoints and corresponding descriptors
for (int idx = 0; idx < 2; idx++) {
    std::vector<bool> isMatched(keypoints[idx].size(), false);

    // Mark all matched keypoint as true
    for (int i = 0; i < matches.size(); i++) {
        if (idx == 0) {
            isMatched[matches[i].queryIdx] = true;
        }
        else {
            isMatched[matches[i].trainIdx] = true;
        }
    }

    std::vector<cv::KeyPoint>::const_iterator itr = keypoints[idx].begin();

    // New descriptor length will be old descriptor length minus matched keypoints size
    int descriptor_length = keypoints[idx].size() - matches.size();

    // Create temporary descriptor of new descriptor length
    cv::Mat tempDescriptor(descriptor_length, descriptor[idx].cols, descriptor[idx].depth());
    int count = 0;
    for (int i = 0; i < isMatched.size(); i++) {
        // Remove matched keypoints
        if (isMatched[i] == true) {
            itr = keypoints[idx].erase(itr);
        }
        else {
            descriptor[idx].row(i).copyTo(tempDescriptor.row(count));
            itr++;
            count++;
        }
    }

    descriptor[idx].release();
    descriptor[idx] = tempDescriptor.clone();
}

希望对您有所帮助。