파이썬으로 텍스처 맵 굽기
Aug 15 2020
블렌더 2.83을 사용합니다. 애드온 (3D-View에서 액세스 가능)의 경우 텍스처 맵을 굽고 싶습니다. 스크립팅 없이도 완벽하게 할 수 있습니다. 그러나 파이썬으로 나는 성공하지 못했습니다.
내 문제를 최소한으로 줄이기 위해 유효한 UV가있는 선택된 개체로 시작합니다. 그런 다음 다음 파이썬 스크립트를 실행합니다.
import bpy
obj = bpy.context.active_object
# Creating a texture node, linked with a new image
mat = obj.data.materials[0]
mat.use_nodes = True
texImage = mat.node_tree.nodes.new('ShaderNodeTexImage')
img = bpy.ops.image.new(name= obj.name + '_BakedTexture')
texImage = img
# !!! No image is linked to the texture node !!!
# Baking to the newly created image
# The following part works if I create the texture node and the assigning of the image by hand
bpy.context.view_layer.objects.active = obj
bpy.ops.object.bake(type='DIFFUSE', save_mode='EXTERNAL', filepath='C:\\TEMP\\baked.png', use_automatic_name=True, width=512, height=512)
내가 놓친 것은 이미지를 텍스처 노드에 올바르게 연결하는 것입니다. 나는 다음과 같은 유사한 질문을 참조했습니다.
Python으로 활성 이미지 노드 설정
그러나 그들의 대답은 도움이되지 않았습니다 (더 이상 호환되지 않는 Blender 2.7 코드).
답변
3 NoobCat Aug 22 2020 at 01:23
몇 가지 기본 단계, 즉 "TEX_IMAGE"유형의 노드를 추가하고 여기에 이미지를 할당 할 것이라고 생각합니다. 따라서:
obj = bpy.context.active_object
# You can choose your texture size (This will be the de bake image)
image_name = obj.name + '_BakedTexture'
img = bpy.data.images.new(image_name,1024,1024)
#Due to the presence of any multiple materials, it seems necessary to iterate on all the materials, and assign them a node + the image to bake.
for mat in obj.data.materials:
mat.use_nodes = True #Here it is assumed that the materials have been created with nodes, otherwise it would not be possible to assign a node for the Bake, so this step is a bit useless
nodes = mat.node_tree.nodes
texture_node =nodes.new('ShaderNodeTexImage')
texture_node.name = 'Bake_node'
texture_node.select = True
nodes.active = texture_node
texture_node.image = img #Assign the image to the node
bpy.context.view_layer.objects.active = obj
bpy.ops.object.bake(type='DIFFUSE', save_mode='EXTERNAL')
img.save_render(filepath='C:\\TEMP\\baked.png')
#In the last step, we are going to delete the nodes we created earlier
for mat in obj.data.materials:
for n in mat.node_tree.nodes:
if n.name == 'Bake_node':
mat.node_tree.nodes.remove(n)
bpy.ops를 최대한 사용하지 마십시오.이 경우에는 bpy.data.images.new () 메소드를 사용하여 이미지를 쉽게 생성 할 수 있습니다. 모든 블렌더 객체는 해당 메소드로 생성 할 수 있습니다.
bpy.data.objects.new()
bpy.data.materials.new()
bpy.data.scenes.new()
...
...
bpy.ops이 경우와 같이 대안이 없을 때만 사용하는 것이 좋습니다. bpy.ops.object.bake()
이것은 당신이 무언가를 생성하고 그것을 변수에 직접 할당 할 수있게합니다. img = bpy.data.images.new()
그래서 당신은 그것에 접근하기 위해 열광 할 필요가 없습니다.