2017年11月21日火曜日

レンダリング画像上の、あるノードのxy座標を取得する方法

レンダリング画像上の、あるノードのxy座標を取得する方法。
OpenMayaを介して、ワールド空間空間内の座標位置をカメラから計算し、画像上のxy座標を算出します。
レンダリング情報はレンダリング設定のcommon設定のresolutionから取得して計算します。

ソースまるコピ:
http://forums.cgsociety.org/archive/index.php?t-1109300.html
非常に分かりやすい記事でした。
import maya.cmds as cmds
import maya.OpenMaya as openMaya
def worldSpaceToImageSpace(camera, worldPoint):
#get the current render resolution
resWidth = cmds.getAttr('defaultResolution.width')
resHeight = cmds.getAttr('defaultResolution.height')
#get the dagPath to the camera shape node to get the world inverse matrix
selList = openMaya.MSelectionList()
selList.add(camera)
dagPath = openMaya.MDagPath()
selList.getDagPath(0,dagPath)
dagPath.extendToShape()
camInvMtx = dagPath.inclusiveMatrix().inverse()
#use a camera function set to get projection matrix, convert the MFloatMatrix
#into a MMatrix for multiplication compatibility
fnCam = openMaya.MFnCamera(dagPath)
mFloatMtx = fnCam.projectionMatrix()
projMtx = openMaya.MMatrix(mFloatMtx.matrix)
#multiply all together and do the normalisation
mPoint = openMaya.MPoint(worldPoint[0],worldPoint[1],worldPoint[2]) * camInvMtx * projMtx;
x = (mPoint[0] / mPoint[3] / 2 + .5) * resWidth
y = (mPoint[1] / mPoint[3] / 2 + .5) * resHeight
return [x,y]
print worldSpaceToImageSpace('persp', (1,2,0))
なお、実際は知らせてみると、Photoshop画像上でx座標は正しい位置を取得しましたが、y座標の上下が逆転しました。
うーん、なんだろ。
以上、備忘録メモ