Interactive viewer
Although Matplotlib serves our purposes for visualization, I want this book to be interactive when reading it online. Every feature we implement in this book will therefore be possible to interact with using controllers. For instance sliders to adjust color balance and brightness.
To achieve this, I have made a helper library called interactive.
In this library, there is a function called interact that can take a
Func together with input parameters and produce an interactive
figure in the book.
If you are interested, you can check out the implementation in
the appendix,
but for now, I will just show the usage.
As before, we import Halide.
This time, we also import the helper interact function mentioned above,
together with a Slider class that allows us to define a control
for our effect:
import halide as hl
from halide_book.interactive import Slider, interact
from halide_book.paths import Paths
import halide.imageio
Next, we set up the Vars and load an image like before:
x = hl.Var("x")
y = hl.Var("y")
c = hl.Var("c")
image_data = halide.imageio.imread(Paths.static / "stuff.png")
We then create a Halide Buffer from the array:
image_buffer = hl.Buffer(image_data)
Before applying any operations on an image, it is often a good idea to turn its contents into 32-bit floating point values. This helps us avoid any artifacts caused by working in the very limited 8-bit color space that the image was loaded from:
image = hl.Func("image")
image[x, y, c] = hl.f32(image_buffer[x, y, c] / 255.0)
This time we also include a Param called "factor"
that will allow us to adjust the amount of darkening to apply:
factor = hl.Param(hl.Float(32), "factor", 1.5)
Finally, we reimplement the darken function.
darken = hl.Func("darken")
darken[x, y, c] = image[x, y, c] / factor
slider = Slider(factor, min_value=1, max_value=10, step=0.1)
interact(
darken,
size=[image_buffer.width(), image_buffer.height(), 3],
controls=[slider],
)