Thursday, July 24, 2008

World point to point on image (Maya Python)

Python version of mapping function from point on world space to point on 2d image.
http://www.highend2d.com/boards/lofiversion/index.php/t242922.html

Just a memo so that you dont't have to reinvent the wheel.


import maya.OpenMaya as OpenMaya

def floatMMatrixToMMatrix_(fm):
mat = OpenMaya.MMatrix()
OpenMaya.MScriptUtil.createMatrixFromList ([
fm(0,0),fm(0, 1),fm(0, 2),fm(0, 3),
fm(1,0),fm(1, 1),fm(1, 2),fm(1, 3),
fm(2,0),fm(2, 1),fm(2, 2),fm(2, 3),
fm(3,0),fm(3, 1),fm(3, 2),fm(3, 3)], mat)
return mat


def WorldPositionToImageCoordinate(cameraName, imageXRes, imageYRes, worldX, worldY, worldZ):
p = OpenMaya.MPoint(worldX, worldY, worldZ)
sl = OpenMaya.MSelectionList()
sl.add(cameraName)
dpathCameraShape=OpenMaya.MDagPath()
sl.getDagPath(0, dpathCameraShape)
dpathCameraShape.extendToShape()
fnc = OpenMaya.MFnCamera(dpathCameraShape.node())
mmatProjection = floatMMatrixToMMatrix_(fnc.projectionMatrix())
mmatInvCamera = dpathCameraShape.inclusiveMatrix().inverse();
projected = p * mmatInvCamera * mmatProjection
imageX = (projected.x/projected.w / 2.0 + 0.5) * imageXRes
imageY = (projected.y/projected.w / 2.0 + 0.5) * imageYRes
return imageX, imageY


#print WorldPositionToImageCoordinate('persp', 720, 486, -0.543, 3.926, 7.532)

2 comments:

Anonymous said...

thanks a lot i was looking for this for ages.

hohehohe2 [at] gmail.com said...

you're welcome!