# How do I re-initialize a deleted image?

My script creates an image, bakes to it and saves it. The first time, it works. However, if I try to re-bake to the same image, and in the mean time the user decides to delete the image from disk for whatever reason, bake throws an error:

RuntimeError: Error: Uninitialized image


How do I re-initialize an image to solve the user-deletion problem, or, say, to change its resolution?

I tried creating and deleting a new temporary image for each bake, and that sort of works, but if I do this at the end,

baketarget.user_clear()
bpy.data.images.remove(baketarget)


it leaves an unresolved reference in the uv/image editor, if that happens to be open at the time the bake is started. How do I unlink the image from the image editor?

I had the same problem, yet not with scripting, but with my blend file moving to another computer, and I didn't take saved images with me.

Go to UV/Image editor, press N to bring up the properties panel, and in image tab change source to "Generated". You can change the resolution there as well if you need to.

As for scripting, you probably need to do

bpy.data.images["your_bake_texture"].source = 'GENERATED'

I haven't tried it myself, but I suppose it is what you need, that's what the info panel shows when I change source. It works from console at least.

EDIT1: a quick script to reinitialize all images in all materials in the active object, provided you have selected the image texture nodes in all materials (you need to do this to bake your textures anyway):

import bpy

for slot in bpy.context.active_object.material_slots:

mat = slot.material

imag = mat.node_tree.nodes.active.image

imag.source = 'GENERATED'