Calculating the fraction of each cell in a grid overlapped by a 2D object
I have an arbitrary rectangular Cartesian grid divided into potentially 10^6 or so rectangular cells. (Arbitrary means that the $x$ grid is along points $x_1,...x_n$ and the same goes for the $y$ grid.) I would like to draw an arbitrary object on top of it (say a rotated rectangle, or a circle), and efficiently calculate what fraction of each cell is overlapped by the object: if the cell is entirely inside the bounds of the object, 1.0; if the cell is entirely outside, 0.0; if half of the cell is covered by the object, 0.5. If you displayed this as an image and scaled it where 1 is black and 0 is white, the result would look like an antialiased drawing of the black object.
My application for this question is in Python, and it seems like this capability might be provided by some existing graphics library. Is there a Python module that will test for the fractional intersection of a rectangle and an arbitrary object? Is there a Python library that can at least efficiently test if a point is inside an arbitrary object like a rotat开发者_开发技巧ed rectangle?
You could use PyCairo, which has fast native routines to do its drawing. It's antialiased by default.
Implementing the drawing algorithms in Python would be very slow.
To find the area of a trapezoid resulting from a polygon-square intersection, you can follow the process described by Sean Barrett at https://nothings.org/gamedev/rasterize/
The shapely
Python library can find the area of a trapezoid and perform point-in-object tests. However, for best performance this sounds like something that you'd want to write in C/C++ and provide numpy bindings.
精彩评论