Quickly drawing grids of rectangles, and updating their colors with VisPy

Here’s a demo run of the code:

Background

From the VisPy website:

VisPy is a Python library for interactive scientific visualization that is designed to be fast, scalable, and easy to use.

While looking for a near real time data visualization alternative to the venerable matplotlib, I came across this jaw dropping demo:

Absolutely insane, achieving that kind of performance in python is amazing to say the least. This demo in particular seems like it would be more likely to come from a pygame application at the least, but looks more like it would be a Unity project.

The VisPy project is massive, but luckily, there is a set of really good examples included in the repo. Reminds me of the Arduino standard library in this way. After through all of running these, I didn’t find exactly what I was looking for.

For how simple the finished product looks, the learning curve on the way there was surprisingly steep. Hopefully this post saves you some time.

Code + Explanation

I’d like to be able to draw a grid n * n rectangles, and control their side lengths and the amount of space between them. Being able to update the color of the rectangle is also a requirement.

The goal is to be able to visualize audio signals on a low resolution grid of LEDs.
This software is to be the basis for iterating on ideas and working out bugs without having to redesign hardware.

This example uses a single vispy.visuals.collections.PolygonCollection object to draw the rectangles rather than using a bunch of RectangleVisual objects. Moreover, I found that once there were hundreds of these RectangleVisual objects, I could not achieve the FPS range I was after.  Searching online, I found an explanation for this here:

Any solution that requires more than 10 visuals will perform terribly as it requires a separate GL program for each visual. Each program is drawn sequentially so it takes the GPU a long time to get through each one. It would be best to have one visual that draws all of these rectangles with the appropriate color (I’d never heard of a wafermap before)

So reader, if you’re working on something similar, I hope this snippet is a good starting point:

With a grid of 100 x 100, I’m able update the visual at ~30 FPS, which is way more that I would ever need for my application. If you wanted to extend this to more objects, it seems like the bet approach is to use markers.

Thanks for reading.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.