Skip to content

Discover the bounding box of objects in Maya using Python

A quick guide on how to discover the bounding box of your Maya objects using Python. This is useful if you were creating a tool which handles alignment, scale or transforms based on surrounding objects.

As always, as we will be using the Maya commands library we need to import it, we’ll also use the pretty print module to display our bounding box values in a readable way.

from maya import cmds
import pprint

Then define our function:

def boundingBox():

Create a couple of objects and store the names of each:

 # Create a couple of objects
cube = cmds.polyCube()
sphere = cmds.polySphere()

# Get the shapes of both objects
cubeShape = cube[0]
sphereShape = sphere[0]

Select both objects:

cmds.select(cubeShape, sphereShape)

Add the selected objects to a new variable:

nodes = cmds.ls(selection=True)

Create an empty list which we’ll use to store our bounding box values within our loop:

bboxes = {}

Now that we have our 2 objects stored in our nodes variable, we’ll loop through them:

for node in nodes:

And store the bounding box for each node in a new ‘bbox’ variable:

bbox = cmds.exactWorldBoundingBox(node)

Add the value of bbox into the bboxes list:

bboxes[node] = bbox

And finally we’ll print the bounding box for each node in the loop:

print node, bbox

Output:

pCube1 [-0.5, -0.5, -0.5, 0.5, 0.5, 0.5]
pSphere1 [-1.000000238418579, -1.0, -1.0000004768371582, 1.0, 1.0, 1.0000001192092896]

And if we print the bboxes list (Using the pretty print module):

print pprint.pprint(bboxes)
{u'pCube2': [-0.5, -0.5, -0.5, 0.5, 0.5, 0.5],
u'pSphere2': [-1.000000238418579,
-1.0,
-1.0000004768371582,
1.0,
1.0,
1.0000001192092896]}

These values look a bit confusing, let me explain, the values represent the min and max values:

X MinY MinZ MinX MaxY MaxZ Max
[-0.5-0.5-0.50.50.50.5]

For example X min and X max mean that along the X axis, the bounding box starts at -0.5 and ends at 0.5, we can determine from this that the object is in the centre of the scene, and it ‘1’ in scale along the X axis:

Published inMayaObject ManipulationObjectsscripting