Blame examples/denoising.cc

Packit ea1746
// Ceres Solver - A fast non-linear least squares minimizer
Packit ea1746
// Copyright 2015 Google Inc. All rights reserved.
Packit ea1746
// http://ceres-solver.org/
Packit ea1746
//
Packit ea1746
// Redistribution and use in source and binary forms, with or without
Packit ea1746
// modification, are permitted provided that the following conditions are met:
Packit ea1746
//
Packit ea1746
// * Redistributions of source code must retain the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer.
Packit ea1746
// * Redistributions in binary form must reproduce the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer in the documentation
Packit ea1746
//   and/or other materials provided with the distribution.
Packit ea1746
// * Neither the name of Google Inc. nor the names of its contributors may be
Packit ea1746
//   used to endorse or promote products derived from this software without
Packit ea1746
//   specific prior written permission.
Packit ea1746
//
Packit ea1746
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
Packit ea1746
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Packit ea1746
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
Packit ea1746
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
Packit ea1746
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Packit ea1746
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
Packit ea1746
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
Packit ea1746
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
Packit ea1746
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
Packit ea1746
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
Packit ea1746
// POSSIBILITY OF SUCH DAMAGE.
Packit ea1746
//
Packit ea1746
// Author: strandmark@google.com (Petter Strandmark)
Packit ea1746
//
Packit ea1746
// Denoising using Fields of Experts and the Ceres minimizer.
Packit ea1746
//
Packit ea1746
// Note that for good denoising results the weighting between the data term
Packit ea1746
// and the Fields of Experts term needs to be adjusted. This is discussed
Packit ea1746
// in [1]. This program assumes Gaussian noise. The noise model can be changed
Packit ea1746
// by substituing another function for QuadraticCostFunction.
Packit ea1746
//
Packit ea1746
// [1] S. Roth and M.J. Black. "Fields of Experts." International Journal of
Packit ea1746
//     Computer Vision, 82(2):205--229, 2009.
Packit ea1746
Packit ea1746
#include <algorithm>
Packit ea1746
#include <cmath>
Packit ea1746
#include <iostream>
Packit ea1746
#include <vector>
Packit ea1746
#include <sstream>
Packit ea1746
#include <string>
Packit ea1746
Packit ea1746
#include "ceres/ceres.h"
Packit ea1746
#include "gflags/gflags.h"
Packit ea1746
#include "glog/logging.h"
Packit ea1746
Packit ea1746
#include "fields_of_experts.h"
Packit ea1746
#include "pgm_image.h"
Packit ea1746
Packit ea1746
DEFINE_string(input, "", "File to which the output image should be written");
Packit ea1746
DEFINE_string(foe_file, "", "FoE file to use");
Packit ea1746
DEFINE_string(output, "", "File to which the output image should be written");
Packit ea1746
DEFINE_double(sigma, 20.0, "Standard deviation of noise");
Packit ea1746
DEFINE_bool(verbose, false, "Prints information about the solver progress.");
Packit ea1746
DEFINE_bool(line_search, false, "Use a line search instead of trust region "
Packit ea1746
            "algorithm.");
Packit ea1746
Packit ea1746
namespace ceres {
Packit ea1746
namespace examples {
Packit ea1746
Packit ea1746
// This cost function is used to build the data term.
Packit ea1746
//
Packit ea1746
//   f_i(x) = a * (x_i - b)^2
Packit ea1746
//
Packit ea1746
class QuadraticCostFunction : public ceres::SizedCostFunction<1, 1> {
Packit ea1746
 public:
Packit ea1746
  QuadraticCostFunction(double a, double b)
Packit ea1746
    : sqrta_(std::sqrt(a)), b_(b) {}
Packit ea1746
  virtual bool Evaluate(double const* const* parameters,
Packit ea1746
                        double* residuals,
Packit ea1746
                        double** jacobians) const {
Packit ea1746
    const double x = parameters[0][0];
Packit ea1746
    residuals[0] = sqrta_ * (x - b_);
Packit ea1746
    if (jacobians != NULL && jacobians[0] != NULL) {
Packit ea1746
      jacobians[0][0] = sqrta_;
Packit ea1746
    }
Packit ea1746
    return true;
Packit ea1746
  }
Packit ea1746
 private:
Packit ea1746
  double sqrta_, b_;
Packit ea1746
};
Packit ea1746
Packit ea1746
// Creates a Fields of Experts MAP inference problem.
Packit ea1746
void CreateProblem(const FieldsOfExperts& foe,
Packit ea1746
                   const PGMImage<double>& image,
Packit ea1746
                   Problem* problem,
Packit ea1746
                   PGMImage<double>* solution) {
Packit ea1746
  // Create the data term
Packit ea1746
  CHECK_GT(FLAGS_sigma, 0.0);
Packit ea1746
  const double coefficient = 1 / (2.0 * FLAGS_sigma * FLAGS_sigma);
Packit ea1746
  for (unsigned index = 0; index < image.NumPixels(); ++index) {
Packit ea1746
    ceres::CostFunction* cost_function =
Packit ea1746
        new QuadraticCostFunction(coefficient,
Packit ea1746
                                  image.PixelFromLinearIndex(index));
Packit ea1746
    problem->AddResidualBlock(cost_function,
Packit ea1746
                              NULL,
Packit ea1746
                              solution->MutablePixelFromLinearIndex(index));
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Create Ceres cost and loss functions for regularization. One is needed for
Packit ea1746
  // each filter.
Packit ea1746
  std::vector<ceres::LossFunction*> loss_function(foe.NumFilters());
Packit ea1746
  std::vector<ceres::CostFunction*> cost_function(foe.NumFilters());
Packit ea1746
  for (int alpha_index = 0; alpha_index < foe.NumFilters(); ++alpha_index) {
Packit ea1746
    loss_function[alpha_index] = foe.NewLossFunction(alpha_index);
Packit ea1746
    cost_function[alpha_index] = foe.NewCostFunction(alpha_index);
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Add FoE regularization for each patch in the image.
Packit ea1746
  for (int x = 0; x < image.width() - (foe.Size() - 1); ++x) {
Packit ea1746
    for (int y = 0; y < image.height() - (foe.Size() - 1); ++y) {
Packit ea1746
      // Build a vector with the pixel indices of this patch.
Packit ea1746
      std::vector<double*> pixels;
Packit ea1746
      const std::vector<int>& x_delta_indices = foe.GetXDeltaIndices();
Packit ea1746
      const std::vector<int>& y_delta_indices = foe.GetYDeltaIndices();
Packit ea1746
      for (int i = 0; i < foe.NumVariables(); ++i) {
Packit ea1746
        double* pixel = solution->MutablePixel(x + x_delta_indices[i],
Packit ea1746
                                               y + y_delta_indices[i]);
Packit ea1746
        pixels.push_back(pixel);
Packit ea1746
      }
Packit ea1746
      // For this patch with coordinates (x, y), we will add foe.NumFilters()
Packit ea1746
      // terms to the objective function.
Packit ea1746
      for (int alpha_index = 0; alpha_index < foe.NumFilters(); ++alpha_index) {
Packit ea1746
        problem->AddResidualBlock(cost_function[alpha_index],
Packit ea1746
                                  loss_function[alpha_index],
Packit ea1746
                                  pixels);
Packit ea1746
      }
Packit ea1746
    }
Packit ea1746
  }
Packit ea1746
}
Packit ea1746
Packit ea1746
// Solves the FoE problem using Ceres and post-processes it to make sure the
Packit ea1746
// solution stays within [0, 255].
Packit ea1746
void SolveProblem(Problem* problem, PGMImage<double>* solution) {
Packit ea1746
  // These parameters may be experimented with. For example, ceres::DOGLEG tends
Packit ea1746
  // to be faster for 2x2 filters, but gives solutions with slightly higher
Packit ea1746
  // objective function value.
Packit ea1746
  ceres::Solver::Options options;
Packit ea1746
  options.max_num_iterations = 100;
Packit ea1746
  if (FLAGS_verbose) {
Packit ea1746
    options.minimizer_progress_to_stdout = true;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  if (FLAGS_line_search) {
Packit ea1746
    options.minimizer_type = ceres::LINE_SEARCH;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
Packit ea1746
  options.function_tolerance = 1e-3;  // Enough for denoising.
Packit ea1746
Packit ea1746
  ceres::Solver::Summary summary;
Packit ea1746
  ceres::Solve(options, problem, &summary);
Packit ea1746
  if (FLAGS_verbose) {
Packit ea1746
    std::cout << summary.FullReport() << "\n";
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Make the solution stay in [0, 255].
Packit ea1746
  for (int x = 0; x < solution->width(); ++x) {
Packit ea1746
    for (int y = 0; y < solution->height(); ++y) {
Packit ea1746
      *solution->MutablePixel(x, y) =
Packit ea1746
          std::min(255.0, std::max(0.0, solution->Pixel(x, y)));
Packit ea1746
    }
Packit ea1746
  }
Packit ea1746
}
Packit ea1746
}  // namespace examples
Packit ea1746
}  // namespace ceres
Packit ea1746
Packit ea1746
int main(int argc, char** argv) {
Packit ea1746
  using namespace ceres::examples;
Packit ea1746
  std::string
Packit ea1746
      usage("This program denoises an image using Ceres.  Sample usage:\n");
Packit ea1746
  usage += argv[0];
Packit ea1746
  usage += " --input=<noisy image PGM file> --foe_file=<FoE file name>";
Packit ea1746
  CERES_GFLAGS_NAMESPACE::SetUsageMessage(usage);
Packit ea1746
  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
Packit ea1746
  google::InitGoogleLogging(argv[0]);
Packit ea1746
Packit ea1746
  if (FLAGS_input.empty()) {
Packit ea1746
    std::cerr << "Please provide an image file name.\n";
Packit ea1746
    return 1;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  if (FLAGS_foe_file.empty()) {
Packit ea1746
    std::cerr << "Please provide a Fields of Experts file name.\n";
Packit ea1746
    return 1;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Load the Fields of Experts filters from file.
Packit ea1746
  FieldsOfExperts foe;
Packit ea1746
  if (!foe.LoadFromFile(FLAGS_foe_file)) {
Packit ea1746
    std::cerr << "Loading \"" << FLAGS_foe_file << "\" failed.\n";
Packit ea1746
    return 2;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Read the images
Packit ea1746
  PGMImage<double> image(FLAGS_input);
Packit ea1746
  if (image.width() == 0) {
Packit ea1746
    std::cerr << "Reading \"" << FLAGS_input << "\" failed.\n";
Packit ea1746
    return 3;
Packit ea1746
  }
Packit ea1746
  PGMImage<double> solution(image.width(), image.height());
Packit ea1746
  solution.Set(0.0);
Packit ea1746
Packit ea1746
  ceres::Problem problem;
Packit ea1746
  CreateProblem(foe, image, &problem, &solution);
Packit ea1746
Packit ea1746
  SolveProblem(&problem, &solution);
Packit ea1746
Packit ea1746
  if (!FLAGS_output.empty()) {
Packit ea1746
    CHECK(solution.WriteToFile(FLAGS_output))
Packit ea1746
        << "Writing \"" << FLAGS_output << "\" failed.";
Packit ea1746
  }
Packit ea1746
Packit ea1746
  return 0;
Packit ea1746
}