Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petebankhead/31291fa61d2032cd2da0e8ef4d24a5d5 to your computer and use it in GitHub Desktop.
Save petebankhead/31291fa61d2032cd2da0e8ef4d24a5d5 to your computer and use it in GitHub Desktop.
Create a rectangle annotation with a specified size
/**
* Create a region annotation with a fixed size in QuPath, based on the current viewer location.
*
* @author Pete Bankhead
*/
import qupath.lib.objects.PathAnnotationObject
import qupath.lib.objects.classes.PathClassFactory
import qupath.lib.roi.RectangleROI
import qupath.lib.scripting.QPEx
// Define the size of the region to create
double sizeMicrons = 200.0
// Get main data structures
def imageData = QPEx.getCurrentImageData()
def server = imageData.getServer()
// Convert size in microns to pixels - QuPath ROIs are defined in pixel units of the full-resolution image
int sizePixels = Math.round(sizeMicrons / server.getAveragedPixelSizeMicrons())
// Get the current viewer & the location of the pixel currently in the center
def viewer = QPEx.getCurrentViewer()
double cx = viewer.getCenterPixelX()
double cy = viewer.getCenterPixelY()
// Create a new Rectangle ROI
def roi = new RectangleROI(cx-sizePixels/2, cy-sizePixels/2, sizePixels, sizePixels)
// Create & new annotation & add it to the object hierarchy
def annotation = new PathAnnotationObject(roi, PathClassFactory.getPathClass("Region"))
imageData.getHierarchy().addPathObject(annotation, false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment