Project texture images on to the mesh through python

I am trying to texture the mesh from images (captured using 6 cameras (top, bottom, left, right, front, back). I am looking to accomplish this via a non-interactive python script. The input obj file has normals, vertices, faces and no uv parameters. I need to

Hello and welcome to BlenderArtists.


I made a script that dynamically:

  1. Creates 6 new materials.
  2. Creates and links 6 image texture nodes to the newly created materials.
  3. Assigns the new materials to a desired cube and also based on what axis a face of the cube is facing.

Video

Pre-existing images

image

Script

import bpy

MATS = ("TOP", "BOTTOM", "FRONT", "BACK", "RIGHT", "LEFT")
OBJ = bpy.data.objects["Cube"]

for m in MATS:
    mat = bpy.data.materials.new(m)
    mat.use_nodes = True

    node_tex = mat.node_tree.nodes.new("ShaderNodeTexImage")
    node_tex.location = [-300,300]
#    node_tex.image = bpy.data.images.load("//your_image.png")
    node_tex.image = bpy.data.images[mat.name]

    links = mat.node_tree.links
    link = links.new(node_tex.outputs[0], mat.node_tree.nodes[0].inputs["Base Color"])
        
    OBJ.data.materials.append(mat)
        
    for p in OBJ.data.polygons:
        # TOP
        if p.normal.z > 0:
            p.material_index = 0
        # BOTTOM
        elif p.normal.z < 0:
            p.material_index = 1
        # FRONT
        elif p.normal.y > 0:
            p.material_index = 2
        # BACK
        elif p.normal.y < 0:
            p.material_index = 3
        # RIGHT
        elif p.normal.x > 0:
            p.material_index = 4
        # LEFT
        elif p.normal.x < 0:
            p.material_index = 5

What could be implemented

  1. I wasn’t sure if wanted to load a external image, so I left a commented line of code which you can use instead of using internally imported images.
  2. Real-time rendering of 6 cameras and assigning the new rendered images as textures for the dynamically created materials.
  3. It would be relatively easy to setup / tweak some of the code to assign the new material indexes automatically, but I left it as is for simplicity’s sake.
  4. Finally, you or I can also easily tweak the script to search for pre-existing materials instead of creating new ones.
2 Likes