Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

150 lines
5.4 KiB

  1. This blog post is the first part of a multi-post series on using quadtrees in Python.
  2. This post goes over quadtrees' basics and how you can implement a basic point quadtree in Python.
  3. Future posts aim to apply quadtrees in image segmentation and analysis.
  4. A quadtree is a data structure where each node has exactly four children. This property makes it particularly suitable for spatial searching.
  5. Quadtrees are generalized as "k-d/k-dimensional" trees when you have more than 4 divisions at each node.
  6. In a point-quadtree, leaf nodes are a single unit of spatial information.
  7. A quadtree is constructed by continuously dividing each node until each leaf node only has a single node inside of it.
  8. However, this partitioning can be modified so that each leaf node contains no more than K elements or that each cell can be at a maximum X large.
  9. This stopping criterion is similar to that of the stopping criteria when creating a decision tree.
  10. Although usually used in two-dimensions, quadtrees can be expanded to an arbitrary amount of dimensions.
  11. The lovely property of quadtrees is that it is a "dimensional reduction" algorithm. Rather than operating in O(n^2) for a traditional linear search in two dimensions, a quadtree can accomplish close to O(log n) time for most operations.
  12. # Implementing a Point Quadtree
  13. To implement a quadtree, we only need a few pieces. First, we need some way to represent our spatial information.
  14. In this application, we are only using points; however, we may choose to associate data with each point for an application.
  15. ```python
  16. class Point():
  17. def __init__(self, x, y):
  18. self.x = x
  19. self.y = y
  20. ```
  21. The second thing that we need is a tree data structure.
  22. Like all tree nodes, it has children; however, what is unique about a quadtree is that each node represents a geometric region.
  23. This geometric region has a shape represented by a location and a width and height. Additionally, if this is a leaf node, we need to have our node store the region's points.
  24. ```python
  25. class Node():
  26. def __init__(self, x0, y0, w, h, points):
  27. self.x0 = x0
  28. self.y0 = y0
  29. self.width = w
  30. self.height = h
  31. self.points = points
  32. self.children = []
  33. def get_width(self):
  34. return self.width
  35. def get_height(self):
  36. return self.height
  37. def get_points(self):
  38. return self.points
  39. ```
  40. To generate the quadtree, we will be taking a top-down approach where we recursively divide the node into four regions until a certain threshold has been satisfied.
  41. In this case, we are stopping division when each node contains less than k nodes.
  42. ```python
  43. def recursive_subdivide(node, k):
  44. if len(node.points)<=k:
  45. return
  46. w_ = float(node.width/2)
  47. h_ = float(node.height/2)
  48. p = contains(node.x0, node.y0, w_, h_, node.points)
  49. x1 = Node(node.x0, node.y0, w_, h_, p)
  50. recursive_subdivide(x1, k)
  51. p = contains(node.x0, node.y0+h_, w_, h_, node.points)
  52. x2 = Node(node.x0, node.y0+h_, w_, h_, p)
  53. recursive_subdivide(x2, k)
  54. p = contains(node.x0+w_, node.y0, w_, h_, node.points)
  55. x3 = Node(node.x0 + w_, node.y0, w_, h_, p)
  56. recursive_subdivide(x3, k)
  57. p = contains(node.x0+w_, node.y0+h_, w_, h_, node.points)
  58. x4 = Node(node.x0+w_, node.y0+h_, w_, h_, p)
  59. recursive_subdivide(x4, k)
  60. node.children = [x1, x2, x3, x4]
  61. def contains(x, y, w, h, points):
  62. pts = []
  63. for point in points:
  64. if point.x >= x and point.x <= x+w and point.y>=y and point.y<=y+h:
  65. pts.append(point)
  66. return pts
  67. def find_children(node):
  68. if not node.children:
  69. return [node]
  70. else:
  71. children = []
  72. for child in node.children:
  73. children += (find_children(child))
  74. return children
  75. ```
  76. The QTree class is used to tie together all the data associated with creating a quadtree.
  77. This class is also used to generate dummy data and graph it using matplotlib.
  78. ```Python
  79. import random
  80. import matplotlib.pyplot as plt # plotting libraries
  81. import matplotlib.patches as patches
  82. class QTree():
  83. def __init__(self, k, n):
  84. self.threshold = k
  85. self.points = [Point(random.uniform(0, 10), random.uniform(0, 10)) for x in range(n)]
  86. self.root = Node(0, 0, 10, 10, self.points)
  87. def add_point(self, x, y):
  88. self.points.append(Point(x, y))
  89. def get_points(self):
  90. return self.points
  91. def subdivide(self):
  92. recursive_subdivide(self.root, self.threshold)
  93. def graph(self):
  94. fig = plt.figure(figsize=(12, 8))
  95. plt.title("Quadtree")
  96. c = find_children(self.root)
  97. print("Number of segments: %d" %len(c))
  98. areas = set()
  99. for el in c:
  100. areas.add(el.width*el.height)
  101. print("Minimum segment area: %.3f units" %min(areas))
  102. for n in c:
  103. plt.gcf().gca().add_patch(patches.Rectangle((n.x0, n.y0), n.width, n.height, fill=False))
  104. x = [point.x for point in self.points]
  105. y = [point.y for point in self.points]
  106. plt.plot(x, y, 'ro') # plots the points as red dots
  107. plt.show()
  108. return
  109. ```
  110. Creating a quadtree where each cell can only contain at the most section will produce a lot of cells.
  111. ![png](media/quad-tree/output_4_1.png)
  112. If we change the hyperparameter to split until there are at most two objects per cell, we get larger cells.
  113. ![png](media/quad-tree/output_5_1.png)
  114. # Future Work
  115. In the future, I plan on making a post on how you can use quadtrees to do image compression.