Search code examples
halide

Halide::Expr' is not contextually convertible to 'bool' -- Storing values of functions in variables


I am new to using Halide and I am playing around with implementing algorithms first. I am trying to write a function which, depending on the value of the 8 pixels around it, either skips to the next pixel or does some processing and then moves on to the next pixel. When trying to write this I get the following compiler error:

84:5: error: value of type 'Halide::Expr' is not contextually convertible to 'bool'

    if(input(x,y) > 0)

I have done all the tutorials and have seen that the select function is an option, but is there a way to either compare the values of a function or store them somewhere?

I also may be thinking about this problem wrong or might not be implementing it with the right "Halide mindset", so any suggestions would be great. Thank you in advance for everything!


Solution

  • The underlying issue here is that, although they are syntactically interleaved, and Halide code is constructed by running C++ code, Halide code is not C++ code and vice versa. Halide code is entirely defined by the Halide::* data structures you build up inside Funcs. if is a C control flow construct; you can use it to conditionally build different Halide programs, but you can't use it inside the logic of the Halide program (inside an Expr/Func). select is to Halide (an Expr which conditionally evaluates to one of two values) as if/else is to C (a statement which conditionally executes one of two sub-statements).

    Rest assured, you're hardly alone in having this confusion early on. I want to write a tutorial specifically addressing how to think about staged programming inside Halide.

    Until then, the short, "how do I do what I want" answer is as you suspected and as Khouri pointed out: use a select.