Beispiel #1
0
class BlenderCameraTranscoder(ITranscoder):
    options = [IntVectorOption(name='size', description='The target size of the image', size=2, min=1, max=4096, default=(64,64))]
    convert_map = {"application/x-blender.object-camera" : {"image/jpg": options},
                   "application/x-blender.object-camera" : {"image/png": options},}
    
    def __init__(self):
        ITranscoder.__init__(self)
        
    def activate(self):
        pass

    def transcode(self, dest_path, file_descr, asset_id, target_mimetype, **options):
        
        path_template = expand_path_template(target_mimetype.template, target_mimetype.mimetype, asset_id, **options)
        path_template = os.path.join(dest_path, path_template)
            
        arguments = ['--', asset_id.subname, path_template]
        arguments.append('--format=PNG')#TODO
        arguments.append('--width='+str(options['size'][0]))
        arguments.append('--height='+str(options['size'][1]))
            
        stdoutdata, stderrdata, returncode = run_blender(file_descr.file.filename, script_path(__file__), arguments)
        
        logger.debug(stdoutdata)
        logger.debug(stderrdata)
        logger.debug(returncode)
        #print(returncode) #Todo: check return code
        
        return path_template
class ImageTranscoder(ITranscoder):
    options = [IntVectorOption(name='size', description='The target size of the image', size=2, min=1, max=4096, default=(-1,-1)),
               FloatOption(name='quality', description='The target quality of the image', min=0.0, max=1.0, default=1.0)]
    convert_map = {"image/jpeg" : {"image/png": options, "image/jpeg": options, "image/x-ms-bmp" : options},
                   "image/png" : {"image/png": options, "image/jpeg": options, "image/x-ms-bmp": options},
                   "image/x-ms-bmp" : {"image/x-ms-bmp": options, "image/png": options, "image/jpeg": options} }

    def __init__(self):
        ITranscoder.__init__(self)

    def activate(self):
        pass

    def transcode(self, dest_path, file_descr, asset_id, target_mimetype, **options):
        file_path = expand_path_template(target_mimetype.template, target_mimetype.mimetype, asset_id, **options)

        try:
          im = Image.open(file_descr.file.filename)
        except IOError:
          print("cannot open", file_descr.file.fileName)
          return False

        if options['size'] != [-1,-1]:
          im.thumbnail(options['size'])

        if im.mode == 'P':
          im = im.convert('RGB')

        full_path = os.path.join(dest_path, file_path)
        if not os.path.exists(os.path.dirname(full_path)):
            os.makedirs(os.path.dirname(full_path))

        im.save(full_path)

        return [file_path]
class ImageTranscoder(ITranscoder):
    options = [IntVectorOption(name='size', description='The target size of the image', size=2, min=1, max=4096, default=(-1,-1))]
    convert_map = {"application/x-blender.image" : {"image/png": options, "image/jpeg": options},
                   "application/x-blender.image" : {"image/png": options, "image/jpeg": options},}

    def __init__(self):
        ITranscoder.__init__(self)

    def activate(self):
        pass

    def transcode(self, dest_path, file_descr, asset_id, target_mimetype, **options):

        file_path = expand_path_template(target_mimetype.template, target_mimetype.mimetype, asset_id, **options)
        full_path = os.path.join(dest_path, file_path)

        arguments = ['--', asset_id.subname, full_path]

        stdoutdata, stderrdata, returncode = run_blender(file_descr.file.filename, script_path(__file__), arguments)

        #print(stdoutdata)
        #print(stderrdata)
        #print(returncode) #Todo: check return code

        try:
          im = Image.open(full_path)
        except IOError:
          print("Cannot open: %s" % full_path)
          return False

        if tuple(options['size']) != (-1,-1):
          im.thumbnail(options['size'])

        if im.mode == 'P':
          im = im.convert('RGB')

        im.save(full_path)

        return [file_path]
class BlenderTranscoder(ITranscoder):
    options = [
        IntVectorOption(name='size',
                        description='The target size of the image',
                        size=2,
                        min=1,
                        max=4096,
                        default=(128, 128)),
        IntOption(name='frames',
                  description='Total number of frames.',
                  min=1,
                  max=4096,
                  default=12),
        IntOption(name='footage',
                  description='Number of frames per line',
                  min=1,
                  max=4096,
                  default=4),
    ]
    convert_map = {
        "application/x-blender.object": {
            "image/jpg-reel": options,
            "image/png-reel": options
        },
        "application/x-blender.mesh": {
            "image/jpg-reel": options,
            "image/png-reel": options
        },
        "application/x-blender.group": {
            "image/jpg-reel": options,
            "image/png-reel": options
        },
    }

    def __init__(self):
        ITranscoder.__init__(self)

    def activate(self):
        pass

    def transcode(self, dest_path, file_descr, asset_id, target_mimetype,
                  **options):
        path_template = expand_path_template(target_mimetype.template,
                                             target_mimetype.mimetype,
                                             asset_id, **options)
        abs_file_path = os.path.join(dest_path, path_template)
        template = Template(path_template + '__${angles}')

        angles = [0.0, 0.1, 0.5]

        width = options['size'][0] * options['footage']
        height = options['size'][1] * (options['frames'] // options['footage'])

        angles = []
        file_paths = []
        for angle in range(0, 628, 628 // 12):
            angle = angle // 100.0
            file_path = template.safe_substitute(angles=angle)
            file_paths.append(file_path)
            angles.append(angle)

        if asset_id.mimetype == 'application/x-blender.mesh':
            datatype = 'mesh'
        elif asset_id.mimetype == 'application/x-blender.group':
            datatype = 'group'
        else:
            datatype = 'object'

        arguments = [
            '--', datatype, asset_id.subname,
            os.path.join(dest_path, template.safe_substitute())
        ]
        arguments.extend(list(map(str, angles)))
        arguments.append('--format=PNG')  # TODO
        arguments.append('--camera_type=PERSPECTIVE')
        arguments.append('--width=' + str(options['size'][0]))
        arguments.append('--height=' + str(options['size'][1]))

        script = os.path.join(os.path.dirname(__file__),
                              '../render/b-script-transcoderblenderrender.py')

        logger.debug(abs_file_path)

        stdoutdata, stderrdata, returncode = run_blender(
            file_descr.file.filename, script, arguments)

        logger.debug(stdoutdata)
        logger.debug(stderrdata)
        logger.debug(returncode)
        # print(returncode) # Todo: check return code

        sprite = Image.new('RGB', (width, height))
        for i, file_path in enumerate(file_paths):
            path = os.path.join(dest_path, file_path)
            tile = Image.open(path)
            x = (i % options['footage']) * options['size'][0]
            y = (i // options['footage']) * options['size'][1]
            sprite.paste(tile, (x, y))

        # sprite.show()
        sprite.save(abs_file_path)

        return [path_template]
class BlenderTranscoder(ITranscoder):
    options = [
        IntVectorOption(name='size',
                        description='The target size of the image',
                        size=2,
                        min=1,
                        max=4096,
                        default=(128, 128)),
        IntOption(name='pages',
                  description='Total number of frames.',
                  min=1,
                  max=4096,
                  default=1),
    ]
    convert_map = {
        "application/x-blender.text": {
            "image/jpg": options,
            "image/png": options
        },
    }

    def __init__(self):
        ITranscoder.__init__(self)

    def activate(self):
        pass

    def transcode(self, dest_path, file_descr, asset_id, target_mimetype,
                  **options):
        path_template = expand_path_template(target_mimetype.template,
                                             target_mimetype.mimetype,
                                             asset_id, **options)
        abs_file_path = os.path.join(dest_path, path_template)
        abs_file_path_txt = abs_file_path + '.txt'

        arguments = [
            '--', asset_id.mimetype, asset_id.subname, abs_file_path_txt
        ]

        logger.debug(abs_file_path)

        stdoutdata, stderrdata, returncode = run_blender(
            file_descr.file.filename, script_path(__file__), arguments)

        logger.debug(stdoutdata)
        logger.debug(stderrdata)
        logger.debug(returncode)
        #print(returncode) #Todo: check return code

        arguments = [
            'convert', '-pointsize', '26', '-resize',
            str(options['size'][0]), abs_file_path_txt + '[0]', abs_file_path
        ]
        # print arguments
        pro = subprocess.Popen(arguments,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        stdoutdata, stderrdata = pro.communicate()
        logger.debug(stdoutdata)
        logger.debug(stderrdata)
        logger.debug(pro.returncode)

        return [path_template]
Beispiel #6
0
class BlenderTranscoder(ITranscoder):
    options = [
        IntVectorOption(name='size',
                        description='The target size of the image',
                        size=2,
                        min=1,
                        max=4096,
                        default=(64, 64)),
        EnumOption(name='camera_type',
                   description='The camera type',
                   choices=('ORTHO', 'PERSPECTIVE'),
                   default='PERSPECTIVE'),
        FloatArrayOption(name='angles',
                         description='The angles',
                         min=0.0,
                         max=3.1415,
                         default=(0.0, ))
    ]
    convert_map = {
        "application/x-blender.object": {
            "image/jpg": options,
            "image/png": options
        },
        "application/x-blender.mesh": {
            "image/jpg": options,
            "image/png": options
        },
        "application/x-blender.group": {
            "image/jpg": options,
            "image/png": options
        },
    }

    def __init__(self):
        ITranscoder.__init__(self)

    def activate(self):
        pass

    def transcode(self, dest_path, file_descr, asset_id, target_mimetype,
                  **options):
        angles = options['angles']
        del options['angles']

        path_template = expand_path_template(target_mimetype.template,
                                             target_mimetype.mimetype,
                                             asset_id, **options)
        path_template = os.path.join(dest_path, path_template)

        file_paths = []
        for angle in angles:
            opts = dict(options)
            opts['angles'] = angle
            file_path = expand_path_template(target_mimetype.template,
                                             target_mimetype.mimetype,
                                             asset_id, **opts)
            file_paths.append(file_path)

        if asset_id.mimetype == 'application/x-blender.mesh':
            datatype = 'mesh'
        elif asset_id.mimetype == 'application/x-blender.group':
            datatype = 'group'
        else:
            datatype = 'object'

        arguments = ['--', datatype, asset_id.subname, path_template]
        arguments.extend(list(map(str, angles)))
        arguments.append('--format=PNG')  # TODO
        arguments.append('--camera_type=PERSPECTIVE')
        arguments.append('--width=' + str(options['size'][0]))
        arguments.append('--height=' + str(options['size'][1]))

        stdoutdata, stderrdata, returncode = run_blender(
            file_descr.file.filename, script_path(__file__), arguments)

        logger.debug(stdoutdata)
        logger.debug(stderrdata)
        logger.debug(returncode)
        # print(returncode) #Todo: check return code

        return file_paths
class Video2ImageTranscoder(ITranscoder):
    """Generic Transcoder class for video2image"""
    options = [
        IntOption(name='second',
                  description='The second from which frame is to be extracted',
                  default=-1,
                  min=-1),
        IntVectorOption(name='size',
                        description='The size of output image in pixels',
                        size=2,
                        min=1,
                        max=4096,
                        default=(-1, -1))
    ]

    convert_map = {
        "video/mp4": {
            "image/png": options,
            "image/jpeg": options
        },
        "video/x-msvideo": {
            "image/png": options,
            "image/jpeg": options
        },
        "video/x-flv": {
            "image/png": options,
            "image/jpeg": options
        },
        "video/quicktime": {
            "image/png": options,
            "image/jpeg": options
        },
        "video/x-matroska": {
            "image/png": options,
            "image/jpeg": options
        },
        "video/mpeg": {
            "image/png": options,
            "image/jpeg": options
        },
    }

    def __init__(self):
        ITranscoder.__init__(self)

    def activate(self):
        pass

    def transcode(self, dest_path, file_descr, asset_id, target_mimetype,
                  **options):

        file_path = expand_path_template(target_mimetype.template,
                                         target_mimetype.mimetype, asset_id,
                                         **options)

        time = file_descr.assets[0].metadata['duration'].string_value.split(
            ':')
        time = eval(time[0]) * 3600 + eval(time[1]) * 60 + eval(time[2])
        if time < options['second']:
            print("Not in range of video", file_descr.file.filename)
            return False

        if options['second'] == -1:
            second = time / 2
        else:
            second = options['second']
        try:
            tmp = tempfile.NamedTemporaryFile(suffix='.jpeg')
            pro = subprocess.Popen([
                'ffmpeg', '-ss',
                str(second), '-i', file_descr.file.filename, '-t', '1', '-r',
                '1', tmp.name, '-y'
            ])
            out, err = pro.communicate()
            if pro.returncode != 0:
                print(
                    'ffmpeg failed %s with error code %d' %
                    (file_descr.file.filename, pro.returncode), err)
                return False
        except OSError:
            print("Cannot open video", file_descr.file.filename)
            return False

        image = Image.open(tmp.name)

        full_path = os.path.join(dest_path, file_path)
        if not os.path.exists(os.path.dirname(full_path)):
            os.makedirs(os.path.dirname(full_path))

        if options['size'] != [-1, -1]:
            image.thumbnail(options['size'])
        image.save(full_path)

        return [file_path]