matlab 白色轮廓形心,opencv PCA 求轮廓的形心

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;

}效果如下图所示

0818b9ca8b590ca3270a3433284dd417.png

关于PCA详细使用,可参考官方例程,opencv3.1.0\sources\samples\cpp\tutorial_code\ml\introduction_to_pca文件夹下的introduction_to_pca.cpp文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值