PCA的详细功能不是很了解。但是,发现用它来求形心非常好。输入为findcontours之后的轮廓点,输出为形心的坐标。
话不多说,上代码。
//开发环境,opencv3.1.0+vs2013
#include
#include
using namespace std;
using namespace cv;
cv::Point chao_getCentroid(std::vector<:point> list);//得到形心坐标,
int main()
{
Mat src = imread("1.png");
if (!src.data || src.empty())
{
cout << "Problem loading image!!!" << endl;
return -1;
}
imshow("src", src);
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
Mat bw;
threshold(gray, bw, 50, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
vector hierarchy;
vector > contours;
Mat bw_back = 255 - bw;
findContours(bw_back, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
for (size_t i = 0; i < contours.size(); ++i)
{
drawContours(src, contours, static_cast(i), Scalar(0, 0, 255), 2, 8, hierarchy, 0);
Point center = chao_getCentroid(contours[i]);
circle(src,center,5,Scalar(0,0,255),-1,8);
}
imshow("output", src);
waitKey(0);
return 0;
}
cv::Point chao_getCentroid(std::vector<:point> list)
{
Point result_point(0,0);
//Construct a buffer used by the pca analysis
int sz = static_cast(list.size());
Mat data_pts = Mat(sz, 2, CV_64FC1);
for (int i = 0; i < data_pts.rows; ++i)
{
data_pts.at(i, 0) = list[i].x;
data_pts.at(i, 1) = list[i].y;
}
//Perform PCA analysis
PCA pca_analysis(data_pts, Mat(), CV_PCA_DATA_AS_ROW);
//Store the center of the object
Point cntr = Point(static_cast(pca_analysis.mean.at(0, 0)),
static_cast(pca_analysis.mean.at(0, 1)));
return cntr;
}效果如下图所示
关于PCA详细使用,可参考官方例程,opencv3.1.0\sources\samples\cpp\tutorial_code\ml\introduction_to_pca文件夹下的introduction_to_pca.cpp文件