How to compute the union polygon of two (or more) rectangles

后端 未结 4 1628
无人及你
无人及你 2021-02-06 10:10

For example we have two rectangles and they overlap. I want to get the exact range of the union of them. What is a good way to compute this?

These are the two overlappi

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 10:40

    For a relatively simple and reliable way, you can work as follows:

    • sort all abscissas (of the vertical sides) and ordinates (of the horizontal sides) independently, and discard any duplicate.

    • this establishes mappings between the coordinates and integer indexes.

    • create a binary image of size NxN, filled with black.

    • for every rectangle, fill the image in white between the corresponding indexes.

    • then scan the image to find the corners, by contour tracing, and revert to the original coordinates.

    This process isn't efficient as it takes time proportional to N² plus the sum of the (logical) areas of the rectangles, but it can be useful for a moderate amount of rectangles. It easily deals with coincidences.


    In the case of two rectangles, there aren't so many different configurations possible and you can precompute all vertex sequences for the possible configuration (a small subset of the 2^9 possible images).

    There is no need to explicitly create the image, just associate vertex sequences to the possible permutations of the input X and Y.

提交回复
热议问题