I’m working on a graphics application where the user can draw any number of Lines (with some thickness from point A to point B), Rectangles, or Ellipses on a canvas.
After they’re done, I have a set of shape data indicating the location of each shape and line drawn and I need to determine how many unique pixels they’ve colored as part of a research project.
My naive algorithm is to implement bool shape.Contains(x,y) for each shape and call it for every drawn shape for every pixel in the image to determine if that pixel was drawn by a line, rectangle or ellipse.
Working the other way, I could create void shape.SetPixels(bool[,] canvas) and have each shape set to true, each pixel it contains. This is what I’ve actually implemented and with large data sets, it’s painfully slow.
I have a feeling that there’s a more direct way to go from the raw shape data to the output that I need without examining every pixel. So my question is, given the set of shape data, is there a O(n) function bool[,] IsColored(int x, int y) {} that can generate a matrix of true/falses for colored pixels more directly than either idea I’ve given?
The two methods you’re talking about are generally your two main options. Either check each pixel as needed, or build some kind of data structure for fast lookup beforehand.
If you have a large canvas, but only a few shapes (thus, relatively few “on” pixels), then it may be best to just record every pixel that is hit by any shape, in a hash for example.
This should be fast for lookup, at the expense of memory, and time to build the HashSet.
But it won’t be quite as fast as your
SetPixels(bool[,] canvas)version, nor using as much memory (in the sparse case we’re talking about).