I am embarking on an project on image processing now. The first task was to generate some images to help model training, since actual images for training are hard to come by. Let us use Blender to generate these images.
In this example, I will create the following directory. The folder image_save is empty; this is where we will save the rendered images. The folder somemodule is to show how to import an external module we would like to include in the project. The file practice.blend is created through Blender. It will start off with a scene containing the following objects: Camera, Cube, Lamp and World and RenderLayers. Also, __init__.py file is, as usual, the required python file use an external module such as somemodule. It can be left empty, or be used just like any other python scripts.
blender /image_save /somemodule //__init__.py //test_mod.py /practice.blend /mytest.py
What to expect? We show how to
- render an image of a cube using python from inside Blender. Then, save the image.
- tilt the same cube, render the image, and then save it as well.
print("test") import bpy obj = bpy.data.objects['Cube'] current_dir = "your\\directory\\to\\blender" print(" - location = ", obj.location) print(" - angle = ", obj.rotation_euler) bpy.data.scenes['Scene'].render.filepath = current_dir + '\\image_save\\mytest\\ggwp.jpg' bpy.ops.render.render( write_still=True ) obj.location = 1.0 obj.rotation_euler = 30 print(" - location (after) = ", obj.location) print(" - angle (after) = ", obj.rotation_euler) bpy.data.scenes['Scene'].render.filepath = current_dir + '\\image_save\\mytest\\ggwp2.jpg' bpy.ops.render.render( write_still=True )
Now we are ready. Inside Blender, after creating new file practice.blend, press SHIFT+F4 to access Blender’s internal python console.
import os, sys, importlib
>>> cur_dir = “your\\directory\\to\\blender”
>>> sys.path.append(cur_dir) # add current path
>>> import somemodule.test_mod
>>> import mytest
test – location = <Vector (0.0000, 0.0000, 0.0000)> – angle = <Euler (x=0.0000, y=0.0000, z=0.0000), order=’XYZ’> – location (after) = <Vector (1.0000, 0.0000, 0.0000)> – angle (after) = <Euler (x=30.0000, y=0.0000, z=0.0000), order=’XYZ’>
and two images, ggwp.png and ggwp2.png are created in image_save/mystest, as shown below.
We have run the script by importing, for example through import mytest. In the case we need to rerun the script, use instead
since import mytest will no longer work.