3
$\begingroup$

I'm trying add a background image to my scene in my Python script. It runs without errors, but I can't see the background image.

Can someone please look at my code below and tell me what I'm doing wrong? (It may be that my camera is not active, but I'm not sure how to activate it.)

import bpy
filepath = r"C:\test\trees.jpg"
img = bpy.data.images.load(filepath)

for area in bpy.context.screen.areas:
  if area.type == 'VIEW_3D':
    pace_data = area.spaces.active
    bg = space_data.background_images.new()
    bg.image = img
    break

cam = bpy.data.cameras.new("Camera")
cam_ob = bpy.data.objects.new("Camera", cam)
bpy.context.scene.camera = cam_ob
bpy.context.scene.objects.link(cam_ob)
bpy.context.scene.objects.active = bpy.context.scene.objects["Camera"]
$\endgroup$
1
$\begingroup$

Essentially you forgot to show the background images.

In the UI, you do this by pressing on the checkbox in the Properties Panel (N) --> Background Images.

enter image description here

In python, you do this by accessing the show_background_images property of the 3D view region within the 3D view space (within the 3D view area). This is what your space_data variable is referencing.

Another thing you could do (added in the last line below) is move directly to viewing through the camera when the script is done, to immediately see your BG image.

import bpy
filepath = r"C:\test\trees.jpg"
img = bpy.data.images.load(filepath)

rv3d = None
for area in bpy.context.screen.areas:
  if area.type == 'VIEW_3D':
    space_data = area.spaces.active

    rv3d = space_data.region_3d # Reference 3D view region
    space_data.show_background_images = True # Show BG images

    bg = space_data.background_images.new()
    bg.image = img
    break

cam = bpy.data.cameras.new("Camera")
cam_ob = bpy.data.objects.new("Camera", cam)
bpy.context.scene.camera = cam_ob
bpy.context.scene.objects.link(cam_ob)
bpy.context.scene.objects.active = bpy.context.scene.objects["Camera"]

rv3d.view_perspective = 'CAMERA' # Go to camera perspective to see your BG iamge
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.