void GraphCut::GridGraph_Individually(int width,int height,int num_pixels,int num_labels) { int *result = new int[num_pixels]; // stores result of optimization try{ GCoptimizationGridGraph *gc = new GCoptimizationGridGraph(width,height,num_labels); std::vector<cv::Vec3b>::iterator it; for ( int i = 0; i < num_pixels; i++ ){ int currentRow = i/this->rawImage.cols; int currentCol = i%this->rawImage.cols; //////////////////////////直接使用initGuess,start cv::Vec3b currentValue = this->initGuess.at<cv::Vec3b>(currentRow,currentCol); it = std::find(this->label2Value.begin(), this->label2Value.end(), currentValue); int label = it - this->label2Value.begin(); for(int labelIndex = 0; labelIndex < this->CLASS_NUMBER; labelIndex++){ if(label == labelIndex){ gc->setDataCost(i,labelIndex,1); }else{ gc->setDataCost(i,labelIndex,4); } } //////////////////////////直接使用initGuess,end //////////////////////////使用GMM,start /*for(int labelIndex = 0; labelIndex < this->CLASS_NUMBER; labelIndex++){ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// double gmmProbability = this->GMMProbability.at<cv::Vec<double,3> >(currentRow,currentCol)[labelIndex]; gc->setDataCost(i,labelIndex,1*-log(gmmProbability)); }*/ //////////////////////////使用GMM,end } // next set up smoothness costs individually for ( int l1 = 0; l1 < num_labels; l1++ ){ for (int l2 = 0; l2 < num_labels; l2++ ){ int cost = (l1-l2)*(l1-l2) <= 32 ? 2*(l1-l2)*(l1-l2):32; gc->setSmoothCost(l1,l2,5*cost); } } //printf("\nBefore optimization energy is %d",static_cast<int>(gc->compute_energy())); //gc->expansion(5);// run expansion for 2 iterations. For swap use gc->swap(num_iterations); gc->swap(5); //printf("\nAfter optimization energy is %d\n",static_cast<int>(gc->compute_energy())); for ( int i = 0; i < num_pixels; i++ ){ result[i] = gc->whatLabel(i); this->resultLabel.at<cv::Vec3b>(i/this->resultLabel.cols, i%this->resultLabel.cols) = this->label2Value.at(result[i]); } delete gc; } catch (GCException e){ e.Report(); } delete [] result; }