0
$\begingroup$

I'm using openCV to process an image that is chosen by the user. For OpenCV I just need to get the path to the image, but I'm unable to find anything in the API which lets me just pick a file path (filtering for image file types, preferably) using the built in file browser.

I've tried registering an operator like so, but when I call it in my script the execution doesn't wait until it returns, so I get an error from the next function complaining that the path is None, while the file browser window is still open.

class SelectImageOperator(bpy.types.Operator, ImportHelper):
    bl_idname = "image.select_image"
    bl_label = "Select Image"
    filename_ext = "*.png;*.jpg;*.jpeg;*.bmp;*.tga;*.tiff;*.exr"

    filter_glob: StringProperty(
        default="*.png;*.jpg;*.jpeg;*.bmp;*.tga;*.tiff;*.exr",
        options={'HIDDEN'}
    )

    def execute(self, context):
        print( "Selected file: " + self.filepath)
        return self.filepath
$\endgroup$

1 Answer 1

1
$\begingroup$

Run a function after user selects the filepath

import bpy
from bpy_extras.io_utils import ImportHelper
from bpy.props import StringProperty

class SelectImageOperator(bpy.types.Operator, ImportHelper):
    bl_idname = "image.select_image"
    bl_label = "Select Image"
    bl_options = {"REGISTER"}
    filename_ext = "*.png;*.jpg;*.jpeg;*.bmp;*.tga;*.tiff;*.exr"

    end_fn = None
    cancel_fn = None

    filter_glob: StringProperty(
        default="*.png;*.jpg;*.jpeg;*.bmp;*.tga;*.tiff;*.exr",
        options={'HIDDEN'}
    )

    def cancel(self, context):
        self.__class__.cancel_fn()

    def execute(self, context):
        self.__class__.end_fn(self.filepath)
        return {"FINISHED"}
    
bpy.utils.register_class(SelectImageOperator)


def main():
    # Header of code you want to run...

    def end_fn(filepath): # Run after user selects path
        print(filepath)

    def cancel_fn():
        print("user canceled")

    SelectImageOperator.end_fn = end_fn
    SelectImageOperator.cancel_fn = cancel_fn
    bpy.ops.image.select_image("INVOKE_DEFAULT")


main()
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .