将质心存储到新数组或向量中

时间:2016-01-06 07:51:57

标签: c++ opencv image-processing

这是图片

This is the image     这是下面的代码

#include“opencv2 / opencv.hpp”

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{

    // Read image
    Mat im = imread("beethoven_ode_to_joy.jpg", IMREAD_GRAYSCALE);

    // Setup SimpleBlobDetector parameters.
    SimpleBlobDetector::Params params;

    // Change thresholds
    params.minThreshold = 10;
    params.maxThreshold = 200;

    // Filter by Area.
    params.filterByArea = true;
    params.minArea = 15;

    // Filter by Circularity
    params.filterByCircularity = true;
    params.minCircularity = 0.1;

    // Filter by Convexity
    params.filterByConvexity = true;
    params.minConvexity = 0.01;

    // Filter by Inertia
    params.filterByInertia = true;
    params.minInertiaRatio = 0.01;


    // Storage for blobs
    vector<KeyPoint> keypoints;


    // Set up detector with params
    SimpleBlobDetector detector(params);

    // Detect blobs
    detector.detect(im, keypoints);

在代码的这一部分打印blob的所有质心,但我需要将blob的质心存储到一个新的向量中

    for (vector<KeyPoint>::iterator it = keypoints.begin(); it != keypoints.end(); ++it)
    {
        KeyPoint k = *it;
        cout << k.pt << endl;
    }

    // Draw detected blobs as red circles.
    // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures
    // the size of the circle corresponds to the size of blob

    Mat im_with_keypoints;
    drawKeypoints(im, keypoints, im_with_keypoints, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);

    // Show blobs
    imshow("keypoints", im_with_keypoints);
    imwrite("a.jpg", im_with_keypoints);
    waitKey(0);

}

1 个答案:

答案 0 :(得分:0)

而不是:

 for (vector<KeyPoint>::iterator it = keypoints.begin(); it != keypoints.end(); ++it)
    {
        KeyPoint k = *it;
        cout << k.pt << endl;
    }

你可以这样做:

 std::vector<decltype(keypoints[0].pt)> vector_of_points;
 keypoints.reserve(keypoints.size());
 for (vector<KeyPoint>::iterator it = keypoints.begin(); it != keypoints.end(); ++it)
 {
     KeyPoint k = *it;
     cout << k.pt << endl;
     vector_of_points.emplace_back(k.pt);
 }

甚至更好:

std::vector<decltype(keypoints[0].pt)> vector_of_points(keypoints.size());
std::transform(std::begin(keypoints),std::end(keypoints),std::begin(vector_of_points),[](KeyPoint const& item){std::cout<<item.pt;return item.pt;});

修改

如果你想访问centriod,你可以这样做:

for(auto& centr:vector_of_points){
    //centr is the centriod
}

如果你想要一个特定的质心。第四个例子:

vector_of_points[4]