Last active
April 18, 2021 17:59
-
-
Save petebankhead/e177b07784460a76d70f89347edd988d to your computer and use it in GitHub Desktop.
Split a rectangle into equal parts along its longest dimension in QuPath v0.2.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
* | |
* @author Pete Bankhead | |
*/ | |
// Number of regions to create | |
int nRegions = 3 | |
// Get selected object | |
def selected = getSelectedObject() | |
if (selected == null) { | |
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' | |
return | |
} | |
// Get the side lengths | |
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) | |
double eps = 0.01 | |
if (Math.abs(d1 - d3) > eps || Math.abs(d4 - d2) > eps) { | |
println 'Points do not appear to form a rectangle!' | |
return | |
} | |
// Get starting point based on longest side | |
int ind = 0 | |
if (d1 < d2) { | |
points.add(0, points.remove(3)) | |
} | |
double x = points[ind].x | |
double y = points[ind].y | |
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) | |
// Add annotations | |
def annotations = [] | |
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[], | |
roi.getImagePlane() | |
) | |
def newAnnotation = PathObjects.createAnnotationObject(polygon) | |
newAnnotation.setName("Tile ${i+1}") | |
annotations << newAnnotation | |
} | |
addObjects(annotations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment