Beispiel #1
0
def getShots(dom, cams, options):
    timeList = cdo.parseTimeString(options.time)
    seqDataList = list()
    shotTag = dom.getElementsByTagName("SHOT")
    # constant used in the loop.
    piTwoRad = math.pi / 360.0
    for node in shotTag:
        shotAttrs = getAttrs(node)

        shot = cdo.MMSequenceData()

        # Get cam index from shot, loop over cams
        # and get the camera that this shot links to.
        shotCam = None
        camIndex = getKey(shotAttrs, 'ci', 'int', default=1)
        if camIndex != 0:
            for cam in cams:
                if cam.index == camIndex:
                    shotCam = cam
                    shot.cameraIndex = int(camIndex)
        shot.cameraName = str(cam.name)
        assert shotCam != None

        # put shot data into shot object.
        shot.name = str(getKey(shotAttrs, 'n', 'str'))
        shot.index = str(getKey(shotAttrs, 'i', 'str'))

        shot.width = int(getKey(shotAttrs, 'w', 'int'))
        shot.height = int(getKey(shotAttrs, 'h', 'int'))
        shot.imageAspectRatio = float(shot.width) / float(shot.height)

        shotCam.focalLength = cdo.KeyframeData()
        shotCam.focal = cdo.KeyframeData()
        shotCam.distortion = cdo.KeyframeData()

        # # initialise list of sequences for camera.
        # shotCam.sequences = list()

        # loop over all frames in the shot.
        halfFbWidth = 0.5 * shotCam.filmbackWidth
        for childNode in node.childNodes:
            if childNode.nodeName == 'IPLN':
                imgAttrs = getAttrs(childNode)
                shot.imagePath = getKey(imgAttrs, 'img', 'path')
            elif childNode.nodeName == 'TRNG':
                trngAttrs = getAttrs(childNode)
                trim = getKey(trngAttrs, 't', 'int')
                length = getKey(trngAttrs, 'd', 'int')
                startFrame = int()
                endFrame = int()
                startFrame = trim
                if length != None:
                    endFrame = trim + (length - 1)
                fps = getKey(trngAttrs, 'f', 'float')
                shot.frameRange = (startFrame, endFrame, fps)
            elif childNode.nodeName == 'CFRM':
                frameAttrs = getAttrs(childNode)

                frame = getKey(frameAttrs, 't', 'int')
                if frame == None:
                    frame = int(0)
                assert frame >= 0

                # ensure the frame is valid.
                # if cdo.isFrameInTimeList(frame, timeList):

                fovx = getKey(frameAttrs, 'fovx', 'float')
                pixelRatio = getKey(frameAttrs,
                                    'pr',
                                    'float',
                                    default=float(1))
                dst = getKey(frameAttrs, 'rd', 'float', default=0.0)
                fovy = float(fovx) / float(pixelRatio)

                # calculate focal length (from the FOV) and the "focal" attribute.
                assert isinstance(shotCam.filmbackWidth, float)
                focalLength = (halfFbWidth) / (math.tan(piTwoRad * fovx))
                focal = (focalLength *
                         float(shot.width)) / shotCam.filmbackWidth

                shotCam.focal.setValue(focal, frame)
                shotCam.focalLength.setValue(focalLength, frame)
                shotCam.distortion.setValue(dst, frame)

        shotCam.focalLength.simplifyData()
        shotCam.focal.simplifyData()
        shotCam.distortion.simplifyData()

        shotCam.sequences.append(shot)

        seqDataList.append(shot)

    assert isinstance(shotCam.sequences, list)
    return seqDataList
Beispiel #2
0
def main(cam, options):
    filePath = options.filePath
    assert filePath != None
    outDir = options.outDir
    timeList = cdo.parseTimeString(options.time)

    assert isinstance(cam, cdo.MMCameraData)
    seq = cdo.MMSequenceData()
    if len(cam.sequences) > 0:
        seq = cam.sequences[0]

    invalidImageMsg = ("DistoIma Script could not be written, "
                       "image path given is invalid, '%s'.")
    if seq.imagePath == None:
        print(invalidImageMsg % seq.imagePath)
        return True

    # Get Image Sequence variables.
    imageSeq = seq.imagePath
    images = cdo.getAllImageSequence(seq.imagePath)
    if len(images) <= 0:
        print(invalidImageMsg % seq.imagePath)
        return True
    seqPad = cdo.getImageSequencePadding(seq.imagePath)
    seqStart, seqEnd = cdo.splitImageSequencePath(seq.imagePath)
    offset = cdo.getImageSequenceStartFrame(seq.imagePath)
    # print 'offset:', repr(offset)

    # get script file syntax, changes based on Operating System.
    binPath = getDistoImaExec()
    scriptExt = getScriptFileExt(opsys='windows')
    comChar = getScriptCommentChar(opsys='windows')
    scriptHeader = getScriptHeader(opsys='windows')
    starterScriptExt = getScriptFileExt()
    starterComChar = getScriptCommentChar()
    starterScriptHeader = getScriptHeader()
    starterRunScript = getRunCommand()

    args = list()
    args.append(binPath)
    args.append('!ACTION FLAG!')
    args.append('!DISTO!')
    args.append('-v')
    args.append('!OVERSCAN FLAG!')
    args.append('-f')
    args.append('!FOCAL!')
    args.append('-k')
    args.append('%.15f' % cam.filmbackWidth)
    args.append('-a')
    args.append('%.15f' % cam.pixelAspectRatio)
    args.append('-p')
    args.append('%.15f,%.15f' %
                (cam.lensCentreX * cam.width, cam.lensCentreY * cam.height))
    args.append('-q')  # JPEG Quality, 100.
    args.append('100')
    args.append('-b')
    args.append('!FRAME!')
    args.append('-e')
    args.append('!FRAME!')
    args.append('"!IN!"')
    args.append('"!OUT!"')

    actions = ['-u', '-d']
    descriptions = [
        cdo.exportDesc.mmUndistortScript, cdo.exportDesc.mmDistortScript
    ]
    suffixes = ['undistort', 'distort']
    for i in range(len(actions)):
        action = actions[i]
        desc = descriptions[i]
        suffix = options.fileSuffix + '_' + suffixes[i]
        preAction = getScriptPreActionCommand(action, opsys='windows')
        scriptFooter = getScriptFooter(action, opsys='windows')
        starterPreAction = getScriptPreActionCommand(action)
        starterScriptFooter = getScriptFooter(action)

        # Get the output file path
        outFilePath = cdo.createOutFileName(filePath, cam.name, desc,
                                            scriptExt, outDir)
        outFileName = p.split(outFilePath)[1]
        msg = "Writing DistoIma Script file to '%s'."
        print(msg % outFileName)

        # create command string
        cmdTemplate = str()
        for arg in args:
            cmdTemplate += '%s ' % arg

        # Write the start-up script.
        starterFilePath = str(outFilePath)
        assert starterFilePath.endswith('.' + scriptExt)
        if scriptExt != starterScriptExt:
            endExt = len(starterFilePath) - len(scriptExt)
            starterFilePath = starterFilePath[:endExt] + starterScriptExt
        cmdStarterFilePath = p.abspath(
            starterFilePath.replace('!CPU!', 'start'))
        f = open(cmdStarterFilePath, "w")
        if not f.closed:
            f.write(scriptHeader)
            for cpu in range(cpuNum):
                cmdFilePath = p.abspath(outFilePath.replace('!CPU!', str(cpu)))
                f.write(starterRunScript % cmdFilePath)
            f.close()

        # loop over number of cores, to write multiple files out.
        imagePathsCutUp = list()
        totalImages = len(images)
        chunkSize = float(totalImages) / cpuNum
        for cpu in range(cpuNum):
            startIndex = int(math.ceil(chunkSize * cpu))
            endIndex = int(math.ceil(chunkSize * (cpu + 1))) - 1
            imagePathsCutUp = images[startIndex:endIndex + 1]
            cmdFilePath = p.abspath(outFilePath.replace('!CPU!', str(cpu)))

            f = open(cmdFilePath, "w")
            if not f.closed:
                f.write(scriptHeader)
                f.write(comChar + ' Camera Name: ' + str(cam.name) +
                        os.linesep)
                f.write(preAction)

                # write distortion parameters
                focalData = cam.focalLength
                focalData.simplifyData()

                # write out per-frame commands.
                for imgPath in imagePathsCutUp:
                    overscan = lookupOverscanFlag(options.useOverscan)
                    cmd = str(cmdTemplate)
                    cmd = cmd.replace('!ACTION FLAG!', action)
                    cmd = cmd.replace('!OVERSCAN FLAG!', overscan)

                    # Get the frame number from image path.
                    frameNum = cdo.getImagePathFrameNumber(imageSeq, imgPath)
                    # print 'frameNum:', repr(frameNum)

                    # only output frames that are valid.
                    if cdo.isFrameInTimeList(frameNum, timeList):

                        # Set Distortion Parameter.
                        d = 0.0
                        if isinstance(cam.distortion, cdo.KeyframeData):
                            d = cam.distortion.getValue(frameNum)
                            assert d != None
                        cmd = cmd.replace('!DISTO!', str(d))

                        # Set Focal Length
                        fl = 0.0
                        if isinstance(focalData, cdo.KeyframeData):
                            fl = focalData.getValue(frameNum)
                            assert fl != None
                        cmd = cmd.replace('!FOCAL!', str(fl))

                        # Get image paths
                        outImgPath = str()
                        inImgPath = str()
                        padStr = '#' * seqPad
                        frameStr = str(frameNum).zfill(seqPad)
                        if seqStart.endswith('.'):
                            outImgPath = seqStart[:-1] + suffix + '.'
                        elif seqStart.endswith('_'):
                            outImgPath = seqStart[:-1] + suffix + '_'
                        elif seqStart.endswith('-'):
                            outImgPath = seqStart[:-1] + suffix + '-'
                        else:
                            outImgPath = seqStart + suffix
                        # inImgPath = seqStart+padStr+seqEnd
                        # outImgPath = outImgPath+padStr+'.'+options.outImageExt
                        inImgPath = seqStart + frameStr + seqEnd
                        outImgPath = outImgPath + frameStr + '.' + options.outImageExt

                        # Replace in/out paths.
                        cmd = cmd.replace('!FRAME!', str(frameNum))
                        cmd = cmd.replace('!IN!',
                                          cdo.convertUnixToWinePath(inImgPath))
                        cmd = cmd.replace(
                            '!OUT!', cdo.convertUnixToWinePath(outImgPath))
                        f.write(cmd + os.linesep + os.linesep)

                f.write(scriptFooter)
                f.close()
    return True
Beispiel #3
0
def main(cam, options):
    filePath = options.filePath
    # offset = options.offset
    outDir = options.outDir
    # if offset == None or not isinstance(offset, int):
    #     offset = 0
    assert filePath != None
    timeList = cdo.parseTimeString(options.time)

    assert isinstance(cam, cdo.TDECameraData)
    seq = cdo.TDESequenceData()
    if len(cam.sequences) > 0:
        seq = cam.sequences[0]

    invalidImageMsg = ("Warp Script could not be written, "
                       "image path given is invalid, '%s'.")
    if seq.imagePath == None:
        print(invalidImageMsg % seq.imagePath)
        return True

    # Get Image Sequence variables.
    images = cdo.getAllImageSequence(seq.imagePath)
    if len(images) <= 0:
        print(invalidImageMsg % repr(seq.imagePath))
        return True
    seqPad = cdo.getImageSequencePadding(seq.imagePath)
    seqStart, seqEnd = cdo.splitImageSequencePath(seq.imagePath)

    # get script file syntax, changes based on Operating System.
    binPath = getWarpExec()
    scriptExt = getScriptFileExt()
    comChar = getScriptCommentChar()
    scriptHeader = getScriptHeader()
    runScript = getRunCommand()

    args = list()
    args.append(binPath)
    args.append('-in')
    args.append('"!IN!"')
    args.append('-out')
    args.append('"!OUT!"')
    args.append('-action')
    args.append('!ACTION!')
    args.append('-model')
    args.append('"%s"' % lensModelName)
    args.append('-parameters')
    args.append('!%s!' % distPara.upper())
    for para in defParas:
        args.append('!%s!' % para.upper())
    args.append('-pixel_aspect')
    args.append('%.15f' % cam.pixelAspectRatio)
    args.append('-lco')
    args.append('%.15f' % cam.lensCentreX)
    args.append('%.15f' % cam.lensCentreY)
    args.append('-filmback')
    args.append('%.15f' % cam.filmbackWidth)
    args.append('%.15f' % cam.filmbackHeight)
    args.append('-overscan')
    args.append('!OVERSCAN!')
    args.append('-verbose')

    actions = ['remove_distortion', 'apply_distortion']
    descriptions = [
        cdo.exportDesc.tdeUndistortScript, cdo.exportDesc.tdeDistortScript
    ]
    suffixes = ['undistort', 'distort']
    for i in range(len(actions)):
        action = actions[i]
        desc = descriptions[i]
        suffix = options.fileSuffix + '_' + suffixes[i]
        preAction = getScriptPreActionCommand(action)
        scriptFooter = getScriptFooter(action)

        # Get the output file path
        outFilePath = cdo.createOutFileName(filePath, cam.name, desc,
                                            scriptExt, outDir)
        outFileName = p.split(outFilePath)[1]
        msg = "Writing Warp Script file to '%s'."
        print(msg % outFileName)

        # create command string
        cmdTemplate = str()
        for arg in args:
            cmdTemplate += '%s ' % arg

        # Write the start-up script.
        cmdStarterFilePath = p.abspath(outFilePath.replace('!CPU!', 'start'))
        f = open(cmdStarterFilePath, "w")
        if not f.closed:
            f.write(scriptHeader)
            for cpu in range(cpuNum):
                cmdFilePath = p.abspath(outFilePath.replace('!CPU!', str(cpu)))
                f.write(runScript % cmdFilePath)
            f.close()

        # loop over number of cores, to write multiple files out.
        imagePathsCutUp = list()
        totalImages = len(images)
        chunkSize = float(totalImages) / cpuNum
        for cpu in range(cpuNum):
            startIndex = int(math.ceil(chunkSize * cpu))
            endIndex = int(math.ceil(chunkSize * (cpu + 1))) - 1
            imagePathsCutUp = images[startIndex:endIndex + 1]
            cmdFilePath = p.abspath(outFilePath.replace('!CPU!', str(cpu)))

            f = open(cmdFilePath, "w")
            if not f.closed:
                f.write(scriptHeader)
                f.write(comChar + ' Camera Name: ' + str(cam.name) +
                        os.linesep)
                f.write(preAction)

                # write distortion parameters
                focalData = cam.focalLength
                focalData.simplifyData()

                # write out per-frame commands.
                for imgPath in imagePathsCutUp:
                    cmd = str(cmdTemplate)
                    cmd = cmd.replace('!ACTION!', action)
                    cmd = cmd.replace('!OVERSCAN!', options.useOverscan)

                    # Get the frame number from image path.
                    frameNum = cdo.getImagePathFrameNumber(
                        seq.imagePath, imgPath)

                    # only output frames that are valid.
                    if cdo.isFrameInTimeList(frameNum, timeList):

                        # Set Distortion Parameter.
                        d = 0.0
                        if isinstance(cam.distortion, cdo.KeyframeData):
                            d = cam.distortion.getValue(frameNum)
                            assert d != None
                        paraStr = '!%s!' % distPara.upper()
                        cmd = cmd.replace(paraStr, str(d))

                        # Set Default Parameters.
                        for para in defParas:
                            d = 0.0
                            if para == 'Anamorphic Squeeze':
                                d = 1.0
                            paraStr = '!%s!' % para.upper()
                            cmd = cmd.replace(paraStr, str(d))

                        # Get image path
                        outImgPath = str()
                        frameStr = str(frameNum).zfill(seqPad)
                        if seqStart.endswith('.'):
                            outImgPath = seqStart[:-1] + suffix + '.'
                        elif seqStart.endswith('_'):
                            outImgPath = seqStart[:-1] + suffix + '_'
                        elif seqStart.endswith('-'):
                            outImgPath = seqStart[:-1] + suffix + '-'
                        else:
                            outImgPath = seqStart + suffix
                        outImgPath = outImgPath + frameStr + seqEnd

                        # Replace in/out paths.
                        cmd = cmd.replace('!IN!', imgPath)
                        cmd = cmd.replace('!OUT!', outImgPath)
                        f.write(cmd + os.linesep + os.linesep)

                f.write(scriptFooter)
                f.close()
    return True
Beispiel #4
0
def main(cam, options):
    filePath = options.filePath
    assert filePath != None
    outDir = options.outDir
    timeList = cdo.parseTimeString(options.time)

    # Get Camera Sequence
    assert isinstance(cam, cdo.TDECameraData)
    seq = cdo.TDESequenceData()
    if len(cam.sequences) > 0:
        seq = cam.sequences[0]

    # Get Image Sequence variables.
    offset = cdo.getImageSequenceStartFrame(seq.imagePath)
    # print 'offset:', repr(offset)

    frameRange = (0, 0, 24)
    if (cam.sequences != None) and (len(cam.sequences) > 0):
        frameRange = cam.sequences[0].frameRange
    nfr = int(frameRange[1] - frameRange[0])
    fbw = cam.filmbackWidth
    fbh = cam.filmbackHeight
    lcx = 0.0
    lcy = 0.0
    pxa = cam.pixelAspectRatio

    outFilePath = cdo.createOutFileName(filePath, cam.name,
                                        cdo.exportDesc.nukeWetaNode, 'nk',
                                        outDir)
    outFileName = p.split(outFilePath)[1]
    msg = "Writing 3DE Weta Nuke Distortion Node file to '%s'"
    print(msg % outFileName)
    f = open(outFilePath, "w")
    if not f.closed:
        f.write('# Exported by %s %s\n' %
                (cdo.projectName, cdo.projectVersion))
        f.write('%s {\n' % lensModel)
        f.write(' direction undistort\n')

        # write Focal length
        focalData = cam.focalLength
        focalData.simplifyData()
        if focalData.static == False:
            f.write(' tde4_focal_length_cm {{curve ')
            for frame in range(1, nfr + 1):
                if cdo.isFrameInTimeList(frame, timeList):
                    f.write('x %i' % (offset + frame))
                    f.write(' %.7f ' % focalData.getValue(frame))
            f.write('}}\n')
        elif focalData.static == True:
            f.write(' tde4_focal_length_cm %.7f \n' % focalData.getValue(0))

        # write camera
        f.write(' tde4_filmback_width_cm %.7f \n' % fbw)
        f.write(' tde4_filmback_height_cm %.7f \n' % fbh)
        f.write(' tde4_lens_center_offset_x_cm %.7f \n' % lcx)
        f.write(' tde4_lens_center_offset_y_cm %.7f \n' % lcy)
        f.write(' tde4_pixel_aspect %.7f \n' % pxa)

        # write distortion parameters
        if cam.distortion.static == False:

            # write distortion parameter
            f.write(' Distortion {{curve ')
            for frame in range(1, nfr + 1):
                if cdo.isFrameInTimeList(frame, timeList):
                    f.write('x %i' % (frame + offset))
                    distValue = cam.distortion.getValue(frame)
                    assert distValue != None
                    f.write(' %.7f ' % distValue)
            f.write('}}\n')

            # write default parameters.
            for para in defParas:
                f.write(' ' + getNukeParameterName(para) + ' {{curve ')
                for frame in range(1, nfr + 1):
                    if cdo.isFrameInTimeList(frame, timeList):
                        f.write('x %i' % (offset + frame))
                        d = 0.0
                        if para == 'Anamorphic Squeeze':
                            d = 1.0
                        f.write(' %.7f ' % d)
                f.write('}}\n')

        elif cam.distortion.static == True:

            # write distortion parameter
            distValue = cam.distortion.getValue(0)
            assert distValue != None
            f.write(' %s %.7f \n' %
                    (getNukeParameterName(distPara), distValue))

            # Write static default parameters
            for para in defParas:
                d = 0.0
                if para == 'Anamorphic Squeeze':
                    d = 1.0
                f.write(' %s %.7f \n' % (getNukeParameterName(para), d))

        nodeName = 'tde4_ldp_%s_%s' % (str(cam.name), str(cam.index))
        if options.nodeName != None:
            nodeName = options.nodeName
        replaceChar = '_'
        illegalChars = [' ', '-', '.', ',']
        for char in illegalChars:
            nodeName = nodeName.replace(char, replaceChar)
        f.write(' name %s\n' % nodeName)
        f.write('}\n')

    f.close()
    return True
def main(cam, options):
    filePath = options.filePath
    assert filePath != None
    outDir = options.outDir
    timeList = cdo.parseTimeString(options.time)

    outFilePath = cdo.createOutFileName(filePath, cam.name,
                                        cdo.exportDesc.tdeLens, 'txt', outDir)
    outFileName = p.split(outFilePath)[1]
    msg = "Writing 3DE Lens file to '%s'."
    print(msg % outFileName)
    f = open(outFilePath, "w")
    if not f.closed:
        # write lens name
        f.write(cam.name + '_lens\n')

        fl = float(3)  # 30mm
        if isinstance(cam.focalLength, cdo.KeyframeData):
            fl = cam.focalLength.getValue(0)
            assert fl != None

        # write lens data
        f.write("%.15f " % (cam.filmbackWidth))
        f.write("%.15f " % (cam.filmbackHeight))
        f.write("%.15f " % (fl))
        f.write("%.15f " % (cam.filmAspectRatio))
        f.write("%.15f " % (float(0)))
        f.write("%.15f " % (float(0)))
        f.write("%.15f\n" % (cam.pixelAspectRatio))

        # write dynamic distortion
        # If the distortion is animated, we must write a curve out for the focus distance.
        if cam.distortion.static:
            f.write("DISTORTION_STATIC\n")
        else:
            f.write("DISTORTION_DYNAMIC_FOCUS_DISTANCE\n")

        # write out model
        f.write("%s\n" % lensModelName)

        # write the distortion value out
        distValue = float(0)
        if isinstance(cam.distortion, cdo.KeyframeData):
            distValue = cam.distortion.getValue(0)
            assert distValue != None
        f.write("%s\n" % (distPara))
        f.write("%.15f\n" % (distValue))
        writeCurve(f, cam.distortion, timeList)

        # write out all other distortion default values
        for para in defParas:
            f.write("%s\n" % (para))
            d = 0.0
            if para == 'Anamorphic Squeeze':
                d = 1.0
            f.write("%.15f\n" % (d))
            writeCurve(f, None, timeList)

        f.write("<end_of_file>\n")
        f.close()
        assert p.isfile(outFilePath) == True
    return True
def main(cam, options):
    filePath = options.filePath
    assert filePath != None
    outDir = options.outDir
    timeList = cdo.parseTimeString(options.time)

    outFilePath = cdo.createOutFileName(filePath, cam.name,
                                        cdo.exportDesc.tdeRawText, 'txt',
                                        outDir)

    outFileName = p.split(outFilePath)[1]
    msg = "Writing 3DE Raw Text file to '%s'."
    print(msg % outFileName)
    f = open(outFilePath, "w")
    if not f.closed:
        # write camera name
        f.write('Camera Name: ' + str(cam.name) + "\n")

        fl = 3.0  # 30mm
        if isinstance(cam.focalLength, cdo.KeyframeData):
            fl = cam.focalLength.getValue(0)
            assert fl != None

        # write lens data
        f.write("Focal Length (%s): %.4f\n" % (cam._units, fl))
        f.write("Filmback Width (%s): %.4f\n" %
                (cam._units, cam.filmbackWidth))
        f.write("Filmback Height (%s): %.4f\n" %
                (cam._units, cam.filmbackHeight))
        f.write("Film Aspect Ratio: %.4f\n" % cam.filmAspectRatio)
        f.write("Lens Centre X (%s): %.4f\n" % (cam._units, 0.0))
        f.write("Lens Centre Y (%s): %.4f\n" % (cam._units, 0.0))
        f.write("Pixel Aspect Ratio: %.4f\n\n" % cam.pixelAspectRatio)

        # write dynamic distortion
        if cam.distortion.static:
            f.write("Static Distortion\n\n")
        else:
            f.write("Animated Distortion\n\n")

        # write the distortion value out
        distValue = 0.0
        if isinstance(cam.distortion, cdo.KeyframeData):
            distValue = cam.distortion.getValue(0)
            assert distValue != None
        f.write("%s\n" % (distPara))
        f.write("%.15f\n" % (distValue))
        writeCurve(f, cam.distortion, timeList)
        f.write("\n")

        # write out all other distortion default values
        for para in defParas:
            f.write("%s\n" % (para))
            d = 0.0
            if para == 'Anamorphic Squeeze':
                d = 1.0
            f.write("%.15f\n" % (d))
            keys = cdo.KeyframeData(static=True, initialValue=d)
            writeCurve(f, keys, timeList)
            f.write("\n")

        f.close()
    return True