Using Firtree from Python (part 1)

I’m going to write a set of blog posts all about how to use Firtree from Python. This post is about the simplest thing that you can do with Firtree, load an image and write it back out again.

To get Firtree on Ubuntu Karmic, you can add the Firtree PPA to your system and install the python-firtree package.

Firtree is based around the concept of a sampler. A sampler in essence knows how to get the colour of a pixel given it’s location. The location is specified as a 2d vector of floats and the colour is a 4d vector of floats. The colour is made up of the red, green, blue and alpha components scaled into the rage zero to one.

Our first example will load our input, the ubiquitous Lena, into a Cairo surface and create a sampler which knows how to get data out of that surface:

 Python |  copy code |? 
1
import cairo
2
import pyfirtree as ft
3
 
4
# Firstly, load the lena image
5
lena_surface = cairo.ImageSurface.create_from_png('lena.png')
6
 
7
# Create a sampler for the surface
8
lena_sampler = ft.CairoSurfaceSampler()
9
lena_sampler.set_cairo_surface(lena_surface)

So far, so easy. Firtree also has the concept of a renderer which knows how to run over each pixel in an output, ask the sampler for the appropriate pixel colour and write it out. Firtree ships with a CPU based renderer which uses LLVM to compile your pipeline down into efficient code and run it over all the CPUs in your machine. Let’s make use of that:

 Python |  copy code |? 
01
# Create an output surface similar to the input
02
output_surface = cairo.ImageSurface(
03
	cairo.FORMAT_ARGB32,
04
	lena_surface.get_width(),
05
	lena_surface.get_height() )
06
 
07
# Create a CPU render engine.
08
engine = ft.CpuRenderer()
09
 
10
# Use the engine to write the input to the output.
11
engine.set_sampler(lena_sampler)
12
engine.render_into_cairo_surface(
13
	lena_sampler.get_extent(), 	# what area of the input to render
14
	output_surface 			# into what
15
	)
16
 
17
# Write the output
18
output_surface.write_to_png('output.png')

And that is it, you have written some code that loads an input file and writes it back out to another file. Next time you’ll learn how to make use of the main feature of Firtree: image processing kernels.

The source code for this example is available.

Comments are closed.