analitics

Pages

Wednesday, May 25, 2022

Blender 3D and python scripting - part 006.

In this tutorial I will show you how to use the camera and render an image.
I kept the source code from the old tutorial 005 and made the following changes:
I defined the global PI constant because I used it outside the definition.
import bpy

#define the pi global 
pi = 3.1415926
I added to the old source code the part of adding camera, translation, rotation, rendering settings and rendering an image called box_640_480.png in the 3D folder on the local disk.
You can see in the example below the added source code:
# define the new camera named NewCamera
camera_data = bpy.data.cameras.new(name='NewCamera')
# set camera_data to object 
camera_object = bpy.data.objects.new('ObjectCamera', camera_data)
# link camera object to scene
bpy.context.scene.collection.objects.link(camera_object)
# set active camera in the current scene by object
bpy.context.scene.camera = bpy.data.objects['ObjectCamera']
# set location 
camera_object.location = [0,-5,1]
# set rotation mode
camera_object.rotation_mode = 'XYZ'
# set the rotate the camerea using rotation_euler
bpy.data.objects[camera_object.name_full].rotation_euler = (90*(pi/180),0,0)

scene = bpy.context.scene

#these settings will set the render output
bpy.context.scene.cycles.samples = 1
scene.render.resolution_x = 640
scene.render.resolution_y = 480
scene.render.resolution_percentage = 100
scene.render.use_border = False
scene.render.image_settings.file_format='PNG'
scene.render.filepath='C:/3D/box_640_480.png'
bpy.ops.render.render(write_still=1)