Search code examples
if-statementhalide

If Statement equivalent in Halide


Need help implementing if equivalent in Halide

if (current_pixel_mag > threshold) {
  mag = 65535;
  ed = 0;
}

I have tried Halide Select, but that is equivalent of ternary operator in C, and does not support multiple statements for given condition.


Solution

  • If I got you right, the following code should do the job:

    Var x, y;
    
    Func mag = ...;
    Func ed = ...;
    
    Expr threshold = ...;
    
    mag(x, y) = select(mag(x, y) > threshold, 65535, mag(x, y));
    ed(x, y) = select(mag(x, y) > threshold, 0, ed(x, y));
    

    It's quite inefficient because of update definitions and it's difficult to schedule two functions in a single loop over x, y.

    That said you could store multiple statements in a single function, then you could use tuples. There are another select function for tuples called tuple_select:

    Func magAndEd;
    magAndEd(x, y) = {mag(x, y), ed(x, y)};
    magAndEd(x, y) = tuple_select(magAndEd(x, y)[0] > threshold, {65535, 0}, magAndEd(x, y));
    

    Also, it might be possible to fold thresholding into initial definition of the magAndEd.