Search code examples
pythonmayapymel

How to collect all cameras in Maya using Python?


How can I collect all the cameras in a Maya scene excluding the default 'perspective, top, front, side' cameras?

I only want to collect the user created cameras.

cameras = cmds.ls(type=('camera'), l=True) or []
print cameras

Do I need to do listRelatives for any reason? I eventually just want to print the world Matrix of each camera.


Solution

  • To weed out default cameras, you could query for startupCamera using the cmds.camera. Here is some code (with comments) to explain.

    Pymel Version

    # Let's use Pymel for fun
    import pymel.core as pm
    
    # Get all cameras first
    cameras = pm.ls(type=('camera'), l=True)
    
    # Let's filter all startup / default cameras
    startup_cameras = [camera for camera in cameras if pm.camera(camera.parent(0), startupCamera=True, q=True)]
    
    # non-default cameras are easy to find now. Please note that these are all PyNodes
    non_startup_cameras_pynodes = list(set(cameras) - set(startup_cameras))
    
    # Let's get their respective transform names, just in-case
    non_startup_cameras_transform_pynodes = map(lambda x: x.parent(0), non_startup_cameras_pynodes)
    
    # Now we can have a non-PyNode, regular string names list of them
    non_startup_cameras = map(str, non_startup_cameras_pynodes)
    non_startup_cameras_transforms = map(str, non_startup_cameras_transform_pynodes)
    

    cmds Version

    import maya.cmds as cmds
    
    # Get all cameras first
    cameras = cmds.ls(type=('camera'), l=True)
    
    # Let's filter all startup / default cameras
    startup_cameras = [camera for camera in cameras if cmds.camera(cmds.listRelatives(camera, parent=True)[0], startupCamera=True, q=True)]
    
    # non-default cameras are easy to find now.
    non_startup_cameras = list(set(cameras) - set(startup_cameras))
    
    # Let's get their respective transform names, just in-case
    non_startup_cameras_transforms = map(lambda x: cmds.listRelatives(x, parent=True)[0], non_startup_cameras)
    

    Some further reading: http://ewertb.soundlinker.com/mel/mel.082.php