Averaging a list of intersecting rectangles
To improve performance, wait for another review with some clever numpy trick.

To make it more Pythonic, it would be better to represent a rectangle with a Rectangle class instead of a simple tuple, for example:

class Rectangle(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def intersect(self, other):
        hoverlaps = (self.x &lt;= other.x + other.width) and (self.x + self.width &gt;= other.x)
        voverlaps = (self.y &lt;= other.y + other.height) and (self.y + self.height &gt;= other.y)

        return hoverlaps and voverlaps


The intersect method fits naturally into it, and now the code is easier to read.

The averaging method becomes:

def average_rects(rects):
    x = np.average([rect.x for rect in rects])
    y = np.average([rect.y for rect in rects])
    w = np.average([rect.width for rect in rects])
    h = np.average([rect.height for rect in rects])

    return x, y, w, h, len(rects)


The main part of ordered_average_intersecting_rects becomes:

while rects:
    r1 = rects[0]

    rect_cluster = [r1]

    for r2 in rects[1:]:
        if r1.intersect(r2):
            rect_cluster.append(r2)
            rects.remove(r2)


And in your testing method you can create rects with:

rects = [Rectangle(150, 55, 40, 20),
         Rectangle(160, 40, 20, 20),
         Rectangle(100, 120, 20, 20),
         Rectangle(45, 10, 15, 30),
         Rectangle(50, 25, 25, 20),
         Rectangle(35, 35, 20, 30)]


And of course you can (and should) go further:


average_rects could return a tuple: Rectangle(x, y, w, h), len(rects)
The assertions could use cluster1.x, .y, .width, instead of cryptic [0], [1], ...




You can replace while len(rects) &gt; 0: with simply while rects:, because in Python empty sequences are false. This is recommended on PEP8 too.