Image Processing #1: Using Blender

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

  1. render an image of a cube using python from inside Blender. Then, save the image.
  2. tilt the same cube, render the image, and then save it as well.

mytest.py

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[0] = 1.0
obj.rotation_euler[0] = 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 )

test_mod.py

print("inside test_mod")

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
inside 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

blender1

We have run the script by importing, for example through import mytest. In the case we need to rerun the script, use instead

importlib.reload(mytest)

since import mytest will no longer work.