Search code examples
python2dantialiasing

Sub-pixel accuracy for polygon drawing in python?


I have some scientific data that is very important to draw accurately. It is in the form of many side-sharing polygons (output from voronoi partitioning) that are highly dense, and often smaller than an individual pixel on the canvas. However, I want the value of the pixels to reliably report the integrated brightness of the polygons that lie within them: so, for example, if a pixel is half-covered by a polygon with brightness 1.0 and the other half by another polygon with brightness 0.0, the pixel should be exactly 0.5.

I'm doing this in Python, so ideally there would be some nice library for highly accurate drawing that I could use. Matplotlib has a nasty bug that causes polygons to be drawn slightly smaller than their actual extents[0], leading to background-colored lines around the borders of every polygon even when the polygons tile the plane with no gaps in-between.

[0]https://github.com/matplotlib/matplotlib/issues/2823


Solution

  • This is indeed possible with the excellent Cairo library, specially made for high precision, high performance rendering. Just install the python binding with pip install pycairo.

    Try the following short example. Note how the sub-subpixel rendering causes the blue and red to blend into purple at some pixel locations.

    import cairo
    
    WIDTH, HEIGHT = 32, 32
    
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
    ctx = cairo.Context(surface)
    
    # draw blue triangle
    ctx.move_to(10, 10)
    ctx.line_to(20.5, 10)
    ctx.line_to(20.5, 20)
    ctx.close_path()
    
    ctx.set_source_rgb(0.5, 0.0, 0.0)
    ctx.fill()
    
    # draw blue triangle
    ctx.move_to(10, 15)
    ctx.line_to(20.5, 15)
    ctx.line_to(20.5, 25)
    ctx.close_path()
    
    ctx.set_source_rgb(0.0, 0.0, 0.5)
    ctx.fill()
    
    surface.write_to_png("example.png")
    

    enter image description here