Use blender as a python module

Introduction

Blender has built-in python and can control most internal commands. You can also call it from the GUI console, or you can create a script file and execute it.

Since the main body is blender, the passed script is executed by python built in blender. If you pass the --background option, the GUI will not start, so it will behave as if you were running a python script in the CUI.

blender --background --python hogehoge.py

In case of OSX, it seems that you have to pass the argument with --args option of blender.app.

open -a blender.app --args --background --python hogehoge.py

This is enough to automate blender with python, but conversely, you can also call blender as an external module mainly with python.

How to build such a blender python module is described in here. The build process is tedious and will be explained later. Let's use it first.

Try to render

By default, blender creates a square box, light source, and camera at startup, so let's get the rendering result in the startup state.

import bpy

bpy.ops.render.render()
bpy.data.images['Render Result'].save_render(filepath = '/tmp/image.png')

Prepare hogehoge.py like

$ python3 ./hogehoge.py

Has generated /tmp/image.png.

image.png

Of course, you can do the same by passing hogehoge.py to blender as explained at the beginning.

Blender on Jupyter notebook

By the way, since I brought it to the ring on the python side, it can also be used on jupyter notebook. Then, I want to extract the rendering result as a python array and imshow it. However, after a little research, it seems that there is no way to get the rendering result directly without going through a file. Here is a nice method, but unfortunately blender It didn't work without the GUI. Since it is unavoidable, I will take it via tempfile, but it is quite a loss.

def get_img(size=[480,640]):
    scene = bpy.context.scene
    scene.render.resolution_x = size[1]
    scene.render.resolution_y = size[0]
    scene.render.resolution_percentage = 100
    tmpdir=tempfile.TemporaryDirectory()
    scene.render.filepath=tmpdir.name+"/hoge"
    bpy.ops.render.render(write_still=True)
    img=Image.open(tmpdir.name+"/hoge.png ")
    tmpdir.cleanup()
    return img

Anyway, if you use this, you can see the rendering result on Jupyter notebook as below. I tried plotting while moving it little by little. You can see the jupyter notebook here [http://nbviewer.jupyter.org/github/ashitani/jupyter_examples/blob/master/blender.ipynb).

スクリーンショット 2016-10-16 22.14.13.png

Summary I tried using

As mentioned above, I was able to call blender from the python side.

But when is it more convenient than calling python from blener as at the beginning? One is cooperation with an external library, but I feel that I just set the path with python on the blender side. It's fun to use with jupyter, but there seems to be other ways to google.

After all, it may just be a matter of mood. It's a pain to not be able to exchange images without going through files. Well, if you enjoy using it, I feel like you'll win.

I really wanted to combine it with machine learning, but I've exhausted my efforts in building the environment, so this entry is up to this point.

After this, it is a build edition.

About build

Basically, you can follow Official, but there are some traps, so I will keep a record. The following was done on OS X El Capitan.

Build preparation

It seems that it must be python3 and framework format, so I will use python3 of homebrew.

brew install python3

Drop the blender source. With older sources, cmake may not be able to keep up with the OS and development environment versions, so we'll keep up with the latest sources (though it may have mines).

blender_dev
+-- blender  (from git)
+-- lib      (from svn)
+-- build    (For build)

Work with a folder structure like. If you don't have lib, the build won't pass (addiction point 1: see below).

mkdir blender_dev
cd blender_dev
git clone git://git.blender.org/blender.git
cd blender
git submodule update --init --recursive
git submodule foreach git checkout master
git submodule foreach git pull --rebase origin master
cd ..
mkdir lib
cd lib
svn checkout https://svn.blender.org/svnroot/bf-blender/trunk/lib/darwin-9.x.universal
cd ..
mkdir build

blender/build_files/cmake/platform/platform_apple.cmake Since the default framework path is used on lines 96 and 210 of, specify the path of brew's python3 (addiction point 2).

#-- line 96 ---
#       set(_py_framework "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}")
        set(_py_framework "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/")
...
#-- line 210 ---
#   set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/Python")
    set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/Python")

Build & install

Well, it's finally a build.

cd build
cmake \
-D WITH_PYTHON_INSTALL=OFF \
-D WITH_PLAYER=OFF \
-D WITH_PYTHON_MODULE=ON \
../blender/
make
make install

The execution destination of make install is under bin, and it seems that the necessary modules are copied to the folder called 2.78. After that, the documentation says that if you copy the bpy.so and 2.78 folders to site-packages, it will work, but it will not work unless you have a folder name of release instead of a folder name of 2.78 (addiction point 3: see below).

dest=/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages
cp ./bin/bpy.so ${dest}
cp -R ./bin/2.78 ${dest}
ln -s ${dest}/2.78 ${dest}/release

Now you can import bpy from python3.

Addictive point 1

I was angry as follows if I did not make lib or less.

CMake Error at build_files/cmake/platform/platform_apple.cmake:36 (message):
  Mac OSX requires pre-compiled libs at:
  '/Users/***/git/blender/../lib/darwin-9.x.universal'

As stated in the Official Documentation, you can use the precompiled dependent libraries. Well, this is not a addictive point, but rather a proper reading of the formula.

Addictive point 3

When I import bpy from python3, I get angry and fall as below. I can't seem to find the path to 2.78 / *, and even if I google, I can find a lot of answers like "Did you copy it properly?" I did, but it's no good.

BLT_lang_init: 'locale' data path for translations not found, continuing
bpy: couldnt find 'scripts/modules', blender probably wont start.
Freestyle: couldn't find 'scripts/freestyle/modules', Freestyle won't work properly.
ImportError: No module named 'bpy_types'
ImportError: No module named 'bpy_types'
pyrna_srna_ExternalType: failed to find 'bpy_types' module
ImportError: No module named 'bpy_types'
ImportError: No module named 'bpy_types'
pyrna_srna_ExternalType: failed to find 'bpy_types' module
ImportError: No module named 'bpy_types'
pyrna_srna_ExternalType: failed to find 'bpy_types' module
F1016 18:22:03.065414 2006614016 utilities.cc:322] Check failed: !IsGoogleLoggingInitialized() You called InitGoogleLogging() twice!

The documentation says to copy the 2.78 folder, but I also had to make the 2.78 folder accessible with the release folder name.

Recommended Posts

Use blender as a python module
Use pymol as a python library
Create a Python module
Use youtube_dl as a python module. appendix) Nico Nico Douga HTTP 403 error
Use the e-paper module as a to-do list
[Python] Use a string sequence
Use Remotte as a user
Use DynamoDB as a lock manager
Use fabric as is in python (fabric3)
Use embeddable Python as Vim's Python 3 interface
[Python] Use JSON format data as a dictionary type object
Launch a Python script as a service
Use print in a Python2 lambda expression
Make a relation diagram of Python module
[Python] Sorting collection types as a reference
Use Python external module on Sakura Internet
Python as a strongly, dynamically typed language
Use Django from a local Python script
[Blender x Python] How to use modifiers
Blender 2.9 Python Extrude extrude
Python collections module
use go module
Error when installing a module with Python pip
python memo: Treat lists as a set type
Publish a Python module that calculates meteorological factors
How to add a Python module search path
Use cryptography module to handle OpenSSL in Python
To add a module to python put in Julialang
[Python] A rough understanding of the logging module
I tried adding a Python3 module in C
Use a custom error page in python / tornado
Use python in Docker container as Pycharm interpreter
Let's make a module for Python using SWIG
Use the nghttp2 Python module from Homebrew from pyenv's Python
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
Use thingsspeak from python
A * algorithm (Python edition)
Use config.ini in Python
[Python] Take a screenshot
Python module (Python learning memo ④)
Try to make a Python module in C language
[Python] Use JSON with Python
Use fluentd from python
(Python) Treat integer values as a set of flags
Use dates in Python
A python lambda expression ...
python original module import
How to use the Raspberry Pi relay module Python
Use MySQL from Python
Use mecab with Python3
Use LiquidTap Python Client ③
[Blender] Complement Blender's Python API with a text editor
blender, python, spiral staircase
Use DynamoDB with Python
I made a Python module to translate comment outs
Use a Property Decorator?
Daemonize a Python process
Run Blender with python
blender, python, sphere behavior
[Blender] Use the text drawing module from within the script
Let's use the Python version of the Confluence API module.