1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <math.h>
using namespace std;
int main(void){
cv::Mat img = cv::imread("image.png",CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat thr;
cv::threshold(img,thr,0,255,cv::THRESH_OTSU|cv::THRESH_BINARY_INV);
int count = cv::countNonZero(thr);
if (count == 0)
return 1;
cv::Mat data(2, count, CV_32FC1);
int dataColumnIndex = 0;
uchar * ptrThr = thr.data;
for (int row = 0, k = 0; row < thr.rows ;row++) {
for(int col = 0; col < thr.cols ; col++, k++){
if (ptrThr[k] != 0) {
data.at<float>(0,dataColumnIndex) = (float) col;
data.at<float>(1,dataColumnIndex) = (float) row;
++dataColumnIndex;
}
}
}
int maxComponents = 2;
cv::PCA pca(data, cv::Mat(), CV_PCA_DATA_AS_COL, maxComponents);
vector<float> vAngle;
for(int i = 0 ; i < maxComponents; i++){
float dx = pca.eigenvectors.at<float>(i, 0);
float dy = pca.eigenvectors.at<float>(i, 1);
vAngle.push_back(atan2(dy, dx)); //rad
}
return 0;
} |
Partager