[SOLVED] Remove a specific camera background image via python

I’m making an addon that allows to easily point to some images and add them as a sequence background image to the scene camera:

cam = bpy.context.scene.camera

bpy.context.scene.camera.data.background_images.clear()

img = bpy.data.images.load(notePath)
img.source = 'SEQUENCE'
img.name = 'SketchNotes'
cam.data.show_background_images = True
bg = cam.data.background_images.new()
bg.image = img
bg.image_user.frame_duration = bpy.context.scene.frame_end
bg.image_user.frame_start = 1
bg.frame_method = 'CROP'

Now, since it is intended to be used potentially many times, and each time with new files that make the previous ones outdated, I would like to remove any background image previously made by the addon. And that’s where I am stuck.

From this: CameraBackgroundImages(bpy_struct) — Blender Python API

I figure I should use remove(image), but I can’t figure out how to use it to target only the background images made by my addon. I was hoping I could use the image name SketchNotes to target it.
I can’t either use indexes as in bpy.ops.view3d.background_image_remove(index=0) because I can’t be sure the user will use the background images in any particular order (plus this one requires specific contexts to work).

In the meantime I use bpy.context.scene.camera.data.background_images.clear() as in my second line, which works, but it can annoy some people that would want to keep other background images that should not be bothered by my script.

Thanks for any help!

I got my answer there:

The remove method takes the background image object as argument. So in case of your code snippet:

cam.data.background_images.remove(bg)

And I think you have to call the update method after that to update the UI.

cam.data.background_images.update()

When you don’t have the background image object in memory anymore, but the image name instead, you can always search for it, of course:

for bgi in cam.data.background_images:
    if bgi.image and bgi.image.name == your_added_background_image_name:
        cam.data.background_images.remove(bgi)
        cam.data.background_images.update()
        break

user avatar|
Sietse Brouwer