Alpha Expansion Library
C++ library for the Alpha-Expansion graph-cut algorithm with Python bindings
Loading...
Searching...
No Matches
GreedyStrategy.hpp
Go to the documentation of this file.
1#pragma once
2
5#include <type_traits>
6
15template <typename T>
17public:
20 GreedyStrategy(int max_cycles = 100) : max_cycles_(max_cycles) {}
21
24 int execute(AlphaExpansion<T> &optimizer, EnergyModel<T> &model) const override {
25 int num_labels = model.num_labels();
26 int cycle = 0;
27 bool converged = false;
28
29 while (!converged && cycle < max_cycles_) {
30 T best_energy = model.evaluate_total_energy();
31 int best_alpha = -1;
32 std::vector<int> best_labels = model.get_labels();
33 std::vector<int> current_labels = model.get_labels();
34
35 for (int alpha = 0; alpha < num_labels; ++alpha) {
36 model.set_labels(current_labels);
37 if (optimizer.perform_expansion_move(alpha)) {
38 T new_energy = model.evaluate_total_energy();
39 bool improved = false;
40 if constexpr (std::is_floating_point_v<T>) {
41 improved = (best_energy - new_energy > static_cast<T>(1e-5));
42 } else {
43 improved = (new_energy < best_energy);
44 }
45 if (improved) {
46 best_energy = new_energy;
47 best_alpha = alpha;
48 best_labels = model.get_labels();
49 }
50 }
51 }
52
53 if (best_alpha != -1) {
54 model.set_labels(best_labels);
55 } else {
56 model.set_labels(current_labels);
57 converged = true;
58 }
59 cycle++;
60 }
61 return cycle;
62 }
63
64private:
65 int max_cycles_;
66};
Performs alpha-expansion moves on an EnergyModel using a pluggable max-flow solver.
Definition AlphaExpansion.hpp:20
bool perform_expansion_move(const int alpha_label) const
Attempts a single alpha-expansion move for alpha_label.
Definition AlphaExpansion.hpp:41
Stores the graph and energy costs for the Alpha-Expansion algorithm.
Definition EnergyModel.hpp:17
int num_labels() const
Returns the total number of labels.
Definition EnergyModel.hpp:35
void set_labels(const std::vector< int > &labels)
Replaces the full label vector.
Definition EnergyModel.hpp:48
const std::vector< int > & get_labels() const
Returns the full label vector (one entry per node).
Definition EnergyModel.hpp:44
T evaluate_total_energy(const std::vector< int > &eval_labels) const
Evaluates the total energy for a given label assignment.
Definition EnergyModel.hpp:166
Abstract base class for alpha-expansion iteration strategies.
Definition ExpansionStrategy.hpp:32
Expansion strategy that always picks the label with the greatest energy reduction.
Definition GreedyStrategy.hpp:16
int execute(AlphaExpansion< T > &optimizer, EnergyModel< T > &model) const override
Runs greedy alpha-expansion until convergence or max_cycles.
Definition GreedyStrategy.hpp:24
GreedyStrategy(int max_cycles=100)
Constructs the strategy.
Definition GreedyStrategy.hpp:20