p2or
9/23/2016 - 6:45 PM

An operator example which inverts the red channel of certain frames in the UV/Image Editor

An operator example which inverts the red channel of certain frames in the UV/Image Editor

# http://blender.stackexchange.com/q/63561 and http://blender.stackexchange.com/q/3527

import bpy
import os

# format integer with leading zeros
def format_numbers(number, length):
    return '_%0*d' % (length, number)

def create_image_and_save_as_jpg(pixels, clp_name, clp_size, clp_frame):
    # filename with suffix
    filename = clp_name + format_numbers(clp_frame, 4) + ".jpg"
    # create new image
    image = bpy.data.images.new(filename, width=clp_size[0], height=clp_size[1])
    # assign the pixels
    image.pixels = pixels
    # get the output path from global render settings
    output_path = bpy.context.scene.render.filepath
    # join the name and output path
    image.filepath_raw = os.path.join(output_path, image.name)
    # set the file format
    image.file_format = 'JPEG'
    image.save()
    #bpy.data.images.remove(image)


class MovieClipOperator(bpy.types.Operator):
    bl_idname="image.invert_channel"
    bl_label="Invert Red Channel and Save as JPEG"

    @classmethod
    def poll(cls, context):
        spc = context.space_data
        source = ["MOVIE", "SEQUENCE"]
        return (spc.type == 'IMAGE_EDITOR' and spc.image.source in source)

    def execute(self, context):
        spc = context.space_data
        
        # clip and space attributes
        clp = spc.image
        clp_usr = spc.image_user
        clp_usr_current = clp_usr.frame_current
        clp_usr_start = clp_usr.frame_start
        
        # get the current frame
        current_frame = clp_usr_current + clp_usr_start
        
        # get the pixels
        #pixels = spc.image.pixels[:] # read only
        
        # specify the frames
        frame_list = [1,2,3,4,5,6,7,8,9]
        
        # iterate through the list
        for frame in frame_list:
            
            real_frame = frame + clp_usr_start
            
            # set the frame
            clp_usr.frame_offset = real_frame
            
            # force redraw
            spc.draw_channels = "COLOR_ALPHA"
            spc.draw_channels = "COLOR"
            
            # get the pixels and invert red channel
            pixels = list(clp.pixels)
            for i in range(0, len(pixels), 4):
                pixels[i] = 1.0 - pixels[i] 
            
            # create image and save as jpg
            create_image_and_save_as_jpg(pixels, clp.name, clp.size, frame)
            
            # reset the offset value
            clp_usr.frame_offset = 0
        
        self.report({"INFO"}, "Frame {} inverted".format(str(frame_list).strip('[]')))
        return {'FINISHED'}


def register():
    bpy.utils.register_class(MovieClipOperator)

def unregister():
    bpy.utils.unregister_class(MovieClipOperator)

if __name__ == "__main__":
    register()