# Python script to get axis-aligned bounding box

**URL:** https://discourse.slicer.org/t/python-script-to-get-axis-aligned-bounding-box/26227
**Category:** Development
**Created:** [November 14, 2022, 1:37pm UTC](https://discourse.slicer.org/t/python-script-to-get-axis-aligned-bounding-box/26227 "2022-11-14T13:37:33Z")
**Posts on this page:** 1
**Showing post:** 5

<div class="post-metadata">

### Author: ![xackey](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/xackey/32/10860_2.png) [@xackey](https://discourse.slicer.org/u/xackey)
#### Post date: [November 15, 2022, 9:59am UTC](https://discourse.slicer.org/t/python-script-to-get-axis-aligned-bounding-box/26227/5 "2022-11-15T09:59:24Z")

</div>

I was able to make a script but it is very long. Can you make it simpler?

```auto
#Get volume and segmentation
volumeNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLScalarVolumeNode")
segmentationNode = slicer.mrmlScene. GetFirstNodeByClass ("vtkMRMLSegmentationNode")

# Export "Segment_1" to LabelmapNode
labelmapVolumeNode=slicer.mrmlScene.AddNewNodeByClass("vtkMRMLLabelMapVolumeNode")
segmentIds = vtk.vtkStringArray()
segmentId = segmentationNode.GetSegmentation().GetSegmentIdBySegmentName("Segment_1")
segmentIds.InsertNextValue(segmentId)
slicer.modules.segmentations.logic().ExportSegmentsToLabelmapNode(segmentationNode, segmentIds, labelmapVolumeNode, volumeNode)

#Get 3 axis length and center coordinate (kJI coordinate) of a bounding box
import numpy as np
label = array("LabelMapVolume")
points = np.where( label == 1 )
length_z=np.max(points[0])- np.min(points[0])+1
length_y=np.max(points[1])- np.min(points[1])+1
length_x=np.max(points[2])- np.min(points[2])+1
center=[(np.max(points[0])+ np.min(points[0]))/2, (np.max(points[1])+ np.min(points[1]))/2, (np.max(points[2])+ np.min(points[2]))/2]

#Transform KJI to RAS coordinate
ijkToRasMatrix = vtk.vtkMatrix4x4()
volumeNode.GetIJKToRASMatrix(ijkToRasMatrix)
ijkPoint = np.array([center[2], center[1], center[0]]) # This is IJK, opposite order compared to KJI.
rasPoint = ijkToRasMatrix.MultiplyFloatPoint(np.append(ijkPoint,1))

#Make an axis-alinged bounding box of "Segment_1". 
roi=slicer.mrmlScene.AddNewNodeByClass("vtkMRMLAnnotationROINode")
roi.SetXYZ(rasPoint[0], rasPoint[1], rasPoint[2])
spacing = volumeNode.GetSpacing()
roi.SetRadiusXYZ(length_x*spacing[0]/2, length_y*spacing[1]/2, length_z*spacing[2]/2)

```

---

_[View the full topic](https://discourse.slicer.org/t/python-script-to-get-axis-aligned-bounding-box/26227)._
