Search code examples
halide

output shifted in template matching


I'm trying to create a template matching program that's using the following formula to determine the fit between the template and the image:

formula

my code is following:

Halide::Var x, y, xt, yt;
Halide::RDom r(0, t.width(), 0, t.height());
Halide::Func limit, compare;
limit = Halide::BoundaryConditions::constant_exterior(input,255);
compare(x, y) = limit(x,y);
compare(x, y) = Halide::cast<uint8_t>(Halide::pow(t(0 + r.x, 0 + r.y) - limit(x + r.x, y + r.y),2));

Halide::Image<uint8_t> output(input.width(),input.height());
output = compare.realize(input.width(),input.height());

After executing the following code the result image is shifted like in the example:

Original image: Original image

Template: Template

Result: Result

How can I prevent the image from shifting?


Solution

  • Not sure what the types of t and input are, so the following might overflow, but I think you want something like:

    Halide::Var x, y, xt, yt;
    Halide::RDom r(0, t.width(), 0, t.height());
    Halide::Func limit, compare;
    limit = Halide::BoundaryConditions::constant_exterior(input,255);
    compare(x, y) = limit(x,y);
    compare(x, y) = Halide::cast<uint8_t>(sum(Halide::pow(t(r.x, r.y) - limit(x + r.x - t.width()/2, y + r.y - t.height()/2),2))/(t.width()*t.height()));
    
    Halide::Image<uint8_t> output(input.width(),input.height());
    output = compare.realize(input.width(),input.height());