Getting started
Let us begin exploring Halide by generating an image from code.
First we need to import the Halide package.
In this book, we will import it with an alias hl.
import halide as hl
import matplotlib.pyplot as plt
from halide_book.interactive import interact
The core component in Halide is the Func, which is short for "function".
It is defined by giving it a name:
f = hl.Func("f")
The Func can have any number of dimensions.
For now, we will focus on 2D to produce an image.
The Func is defined by assigning a left-hand and right-hand side
for an expression of an arbitrary size.
This is different from for instance NumPy, where you typically work
with a fixed size array.
The way I like to think of defining Halide Func objects is by means
of a coordinate system.
The left hand side contains the coordinates for which we will later
assign the right hand side expression.
Let us visualize this.
First, we need to define the coordinates for x and y.
These are defined using hl.Var:
x = hl.Var("x")
y = hl.Var("y")
Next, we can assign a right hand expression to our Func.
Let us first assign it to x:
f[x, y] = x
To see what the result looks like, we call .realize() on the
Func with the size of the resulting array.
This can then be plotted with matplotlib:
result = f.realize([600, 400])
plt.imshow(result)
plt.colorbar()
plt.show()
As you can see, this produces a gradient in the x-direction.
It represents the x-coordinate in the coordinate system that
defines f.
Similarly we can re-define f and set it to y.
Then we call .realize() again to produce the result.
f = hl.Func("f")
f[x, y] = y
result = f.realize([600, 400])
plt.imshow(result)
plt.colorbar()
plt.show()
This time, we get a gradient in the y-direction, representing the
y coordinate.
Now that we are familiar with the coordinate system, it is time to use it for something a bit more complex. Let us for instance add a sine and cosine function together:
waves = hl.Func("waves")
waves[x, y] = hl.sin(x / 40.0) + hl.cos(y / 60.0)
result = waves.realize([600, 400])
plt.imshow(result)
plt.colorbar()
plt.show()
In this book, we will use Halide to define many complex mathematical operations.
Halide can also be used to perform operations on existing data.
In the next chapter, we will show how to load images and use them
in definitions of our Func objects to create image processing pipelines.