-----------------------------------------------------------------------------------------------
* Split a rectangle into equal parts along its longest dimension.
* Rotated rectangles are supported.
* Written for https://forum.image.sc/t/how-to-divide-annotation-roi-into-equal-dimension-bins/51563/8
* Taken from https://gist.github.com/petebankhead/e177b07784460a76d70f89347edd988d
// Number of regions to create
def selected = getSelectedObject()
println 'No object selected!'
// Get points, removing duplicates
def roi = selected.getROI()
def points = new LinkedHashSet<>(roi.getAllPoints()) as List
if (points.size() != 4) {
println 'I need a ROI with exactly 4 points'
double d1 = points[1].distance(points[0])
double d2 = points[2].distance(points[1])
double d3 = points[3].distance(points[2])
double d4 = points[0].distance(points[3])
// Check we really have a rectangle
// (Set this to a higher number of it's too strict)
if (Math.abs(d1 - d3) > eps || Math.abs(d4 - d2) > eps) {
println 'Points do not appear to form a rectangle!'
// Get starting point based on longest side
points.add(0, points.remove(3))
double dx = (points[ind+1].x - x) / nRegions
double dy = (points[ind+1].y - y) / nRegions
double dx2 = (points[ind+2].x - points[ind+1].x)
double dy2 = (points[ind+2].y - points[ind+1].y)
for (int i = 0; i < nRegions; i++) {
double originX = x + dx*i
double originY = y + dy*i
def polygon = ROIs.createPolygonROI(
[originX, originX+dx, originX+dx+dx2, originX+dx2] as double[],
[originY, originY+dy, originY+dy+dy2, originY+dy2] as double[],
def newAnnotation = PathObjects.createAnnotationObject(polygon)
newAnnotation.setName("ROI 1 Layer ${i+1}") //To change ROI number
annotations << newAnnotation
-----------------------------------------------------------------------------------------------