//用k-means初始化mask,用于二次分割
cv::Mat initImage;
int imgHeight = initImage.rows;
int imgWidth = initImage.cols;
int channel = initImage.channels();
//
cv::Mat kPoins(imgHeight * imgWidth,channel,CV_32F,cv::Scalar(5));
for(int i= 0; i< imgHeight; ++i){
const char *ptr = initImage.ptr<uchar>(i,0);
for(int j= 0; j< imgWidth; ++j, ptr += 3){
const int index = i* imgWidth+ j;
kPoints.at<float>(index,0) = ptr[0];
kPoints.at<float>(index,1) = ptr[1];
kPoints.at<float>(index,2) = ptr[2];
}
}
/*
for(int i= 0; i< imgHeight; ++i){
for(int j= 0; j< imgWidth; ++j){
const int index = i * imgWidth + j;
Vec3b ptr = initImage.at<Vec3b>(i,j);
kPoints.at<float>(index,0) = static_cast<int>(ptr[0]);
kPoints.at<float>(index,1) = static_cast<int>(ptr[1];
kPoints.at<float>(index,2) = static_cast<int>(ptr[2];
}
}
*/
cv::Mat centers(2,1,kPoints.type());
cv::Mat bestLabel;
//k-means
TermCriteria criteria =TermCriteria(TermCriteria::EPS + TermCriteria::COUNT,20,0.1);
kmeans(kPoints, 2, bestLabel, criteria, 5, KMEANS_PP_CENTERS, centers);
const double r = 0.2989, g = 0.5870, b = 1 - r - g;
float center0 = centers.at<float>(0,0) * b + centers.at<float>(0,1) * g + centers.at<float>(0,2) * r;
float center1 = centers.at<float>(1,0) * b + centers.at<float>(1,1) * g + centers.at<float>(1,2) * r;
GrabCutClasses selCenter = {center0 < center1 ? GC_PR_BGD : GC_PR_FGD, center0 < center1 ? GC_PR_FGD : GC_PR_BGD};
cv::Mat mask;
mask.create(imgHeight, imgWidth, CV_8UC1);
for(int i= 0; i< imgHeight; ++i){
const int *ptrLabel = bestLabel.ptr<int>(i * imgWidth,0);
char *maskPtr = mask.ptr<uchar>(i,0);
for(int j= 0; j< imgWidth; ++j){
maskPtr[j] = selCenter [ptrLable[j]];
}
}
/*
cv::Mat mask = Mat::zeros(initImage.size(), initImage.type());
*/