Q:

Calling bpy.ops.object.bake_image() gives error "No valid images found to bake to"

I'm trying to write a script that'll automatically combine different textures each with a unique UV into a common UV. 
This is a portion of my script so far:
# Create new image
bpy.ops.image.new(name=currentImageName, width=1024, height=1024)

# Set bake margins
bpy.context.scene.render.bake_margin = 2

# Set the UV coordinates
ob.data.uv_textures['SmartProject'].active = True

# Specify the bake type
bpy.data.scenes["Scene"].render.bake_type = "TEXTURE"

#Bake the image
bpy.ops.object.bake_image()

When I call this last line, however, I get the error "No valid images found to bake to," in spite of the fact that I just created a new image. I can't find any way to specify which image I want Blender to bake to. 
Thanks for your help

A:

There were a few apparent issues. 
The first is that the I needed to use the function 
ob.data.uv_textures['SmartProject'].data[0].image = bpy.data.images[currentImageName]

to select the correct image. This wasn't enough though, since if the object 'ob' was in edit mode, data would have no elements, returning an index error for data[0].
The next issue was that data has many elements, so I had to actually loop through them setting them all to the current image. The correct code block is now: 
# Create new image
bpy.ops.image.new(name=currentImageName, width=1024, height=1024)

# Set bake margins
bpy.context.scene.render.bake_margin = 2

# Set the UV coordinates
ob.data.uv_textures['SmartProject'].active = True

# Specify the bake type
bpy.data.scenes["Scene"].render.bake_type = "TEXTURE"

# Exit edit mode
bpy.ops.object.mode_set(mode='OBJECT')

# Set the target image
for d in ob.data.uv_textures['SmartProject'].data:
    d.image = bpy.data.images[currentImageName]

# Enter edit mode
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')

#Bake the image
bpy.ops.object.bake_image()

