0

I am new to blender. I have an obj file that contains UV mapping information [extracted using smart UV project]. I have a code that generates random textures as a NumPy array [say 512 x 512 x 3]. I want to apply this image as a texture[uv texture] without saving it to disk and then loading it from the disk. Can we do something like this from the blender python script? I also want to remove previous textures if any. Any suggestions will be helpful. Thank you.

batFINGER
  • 84,216
  • 10
  • 108
  • 233
Dharma
  • 101
  • 1
  • Related: https://blender.stackexchange.com/questions/643/is-it-possible-to-create-image-data-and-save-to-a-file-from-a-script, https://blender.stackexchange.com/questions/92692/how-to-convert-numpy-array-into-image-and-add-it-to-images-inside-bpy there is more for sure. – brockmann Jul 07 '21 at 15:51
  • Thanks @brockmann, the second link looks relevant but that's just adding an image, not UV mapping. – Dharma Jul 07 '21 at 16:01
  • 1
    Could you please clarify. It appears the assumption being made is the numpy array -> image.to use with your models UV Mapping – batFINGER Jul 07 '21 at 17:36
  • Agree with batFINGER. Since all materials are node based, it's not that straight forward as you might guess. I'd recommend use the UI and see what steps are necessary to do what you want and share any example file, preferably using: https://blend-exchange.com/. Also, multiple questions IMHO: How can I create an image out of a numpy array? How can I unwrap an object? How can I assign a shader to an object? What kind of shader? What kind of previous textures? ... Please clearify what exactly you are looking for. – brockmann Jul 07 '21 at 17:40
  • Thanks guys, I don't want to create an image and save it. I have numpy generated array, I have uv unwrapped information [mapping from vertices to textures], I want to apply that array as a texture, does it clarify the question? Thank you. – Dharma Jul 07 '21 at 23:22

1 Answers1

3

Assuming you just need to create the Image

# Your flat array of RGBA float32s
assert len(array) == 4 * width * height

Create image

Note: choose if the image should have alpha here, but even if

it doesn't, the array still needs to be RGBA

img = bpy.data.images.new(img_name, width, height, alpha=False)

Fast way to set pixels (since 2.83)

img.pixels.foreach_set(array)

Pack the image into .blend so it gets saved with it

img.pack()

scurest
  • 10,349
  • 13
  • 31