def mask_roi(rows, cols, bounds): """Return a mask for operating only on pixels inside the given bounds. Parameters ---------- rows, cols : int Shape of the target image. bounds : (M, 3) array of (x, y, 1) coordinates Boundary coordinates. """ # Sort corners clockwise. This can be done with a single # swap operation, but that's a bit more work. mask = (bounds < 1e-14) bounds[mask] -= 0.5 bounds[~mask] += 0.5 centroid = bounds.mean(axis=0) diff = bounds - centroid angle = np.arctan2(diff[:, 1], diff[:, 0]) bounds = bounds[np.argsort(angle)] bounds = np.vstack((bounds, bounds[0])) p = Polygon(bounds[:, 0], bounds[:, 1]) g = Grid(rows, cols) return p.inside(g['cols'].flat, g['rows'].flat).reshape(rows, cols)
print pa print "Area expected: %f, area found: %f" % ((0.85-0.15)**2, pa.area()) print "Centroid: ", pa.centroid() print # concave enclosure test-case for inside. xp = [0.15,0.25,0.45,0.45,0.25,0.25,0.65,0.65,0.85,0.85,0.15] yp = [0.15,0.15,0.15,0.25,0.25,0.55,0.55,0.15,0.15,0.85,0.85] pb = Polygon(xp,yp) xc, yc = pb.centroid() print pb print "Area: ", pb.area() print "Centroid: ", xc, yc print inside = pb.inside(grid_x,grid_y) plt.plot(grid_x[inside], grid_y[inside], 'g.') plt.plot(grid_x[~inside], grid_y[~inside],'r.') plt.plot(pb.x,pb.y, '-k') plt.plot([xc], [yc], 'co') plt.show() # many points in a semicircle, to test speed grid_x,grid_y = np.mgrid[0:1:.01,-1:1:.01].reshape(2,-1) xp = np.sin(np.arange(0,np.pi,0.01)) yp = np.cos(np.arange(0,np.pi,0.01)) pc = Polygon(xp,yp) xc, yc = pc.centroid() print pc
print pa print "Area expected: %f, area found: %f" % ((0.85 - 0.15)**2, pa.area()) print "Centroid: ", pa.centroid() print # concave enclosure test-case for inside. xp = [0.15, 0.25, 0.45, 0.45, 0.25, 0.25, 0.65, 0.65, 0.85, 0.85, 0.15] yp = [0.15, 0.15, 0.15, 0.25, 0.25, 0.55, 0.55, 0.15, 0.15, 0.85, 0.85] pb = Polygon(xp, yp) xc, yc = pb.centroid() print pb print "Area: ", pb.area() print "Centroid: ", xc, yc print inside = pb.inside(grid_x, grid_y) plt.plot(grid_x[inside], grid_y[inside], 'g.') plt.plot(grid_x[~inside], grid_y[~inside], 'r.') plt.plot(pb.x, pb.y, '-k') plt.plot([xc], [yc], 'co') plt.show() # many points in a semicircle, to test speed grid_x, grid_y = np.mgrid[0:1:.01, -1:1:.01].reshape(2, -1) xp = np.sin(np.arange(0, np.pi, 0.01)) yp = np.cos(np.arange(0, np.pi, 0.01)) pc = Polygon(xp, yp) xc, yc = pc.centroid() print pc