const size_t nx = 30;
const size_t ny = 30;
const size_t numberOfLabels = 5;
double lambda = 0.1;
inline size_t variableIndex(const size_t x, const size_t y) {
return x + nx * y;
}
int main() {
Space space(nx * ny, numberOfLabels);
Model gm(space);
for(size_t y = 0; y < ny; ++y)
for(size_t x = 0; x < nx; ++x) {
const size_t shape[] = {numberOfLabels};
for(size_t s = 0; s < numberOfLabels; ++s) {
f(s) = (1.0 - lambda) * rand() / RAND_MAX;
}
Model::FunctionIdentifier fid = gm.addFunction(f);
size_t variableIndices[] = {variableIndex(x, y)};
gm.addFactor(fid, variableIndices, variableIndices + 1);
}
Model::FunctionIdentifier fid = gm.addFunction(f);
for(size_t y = 0; y < ny; ++y)
for(size_t x = 0; x < nx; ++x) {
if(x + 1 < nx) {
size_t variableIndices[] = {variableIndex(x, y), variableIndex(x + 1, y)};
sort(variableIndices, variableIndices + 2);
gm.addFactor(fid, variableIndices, variableIndices + 2);
}
if(y + 1 < ny) {
size_t variableIndices[] = {variableIndex(x, y), variableIndex(x, y + 1)};
sort(variableIndices, variableIndices + 2);
gm.addFactor(fid, variableIndices, variableIndices + 2);
}
}
const size_t maxNumberOfIterations = 40;
const double convergenceBound = 1e-7;
const double damping = 0.5;
BeliefPropagation::Parameter parameter(maxNumberOfIterations, convergenceBound, damping);
BeliefPropagation bp(gm, parameter);
BeliefPropagation::VerboseVisitorType visitor;
bp.infer(visitor);
vector<size_t> labeling(nx * ny);
bp.arg(labeling);
size_t variableIndex = 0;
for(size_t y = 0; y < ny; ++y) {
for(size_t x = 0; x < nx; ++x) {
cout << labeling[variableIndex] << ' ';
++variableIndex;
}
cout << endl;
}
}