Skip to content

Instantly share code, notes, and snippets.

@soravux
Last active January 4, 2017 11:37
Show Gist options
  • Save soravux/8da679a9e2e41ed6a5f03c23eb8cd0cc to your computer and use it in GitHub Desktop.
Save soravux/8da679a9e2e41ed6a5f03c23eb8cd0cc to your computer and use it in GitHub Desktop.

Adding a bunny lit with an environment map to a background using Blender's Cycles renderer.

import sys
import os
import random
import shutil
from os.path import basename as bn
PACKAGE_PARENT = '../..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
from hdrio import imwrite, imread
import numpy as np
from scipy.misc import imresize
output_dir = "renders"
os.makedirs(output_dir, exist_ok=True)
blender_exec = shutil.which('blender')
blender_scene = os.path.join(SCRIPT_DIR, "scene.blend")
python_script = os.path.join(SCRIPT_DIR, "scene.py")
def runBlender():
os.system("{} --background {} --python {}".format(blender_exec, blender_scene, python_script))
def addBackground(im, background):
comp = imresize(im, background.shape[:2]).astype('float32') / 255.
alpha = comp[:,:,3]
alpha3_n = np.tile(1 - alpha[:,:,np.newaxis], [1, 1, 3])
alpha3_p = np.tile(alpha[:,:,np.newaxis], [1, 1, 3])
return background[:,:,:3]*alpha3_n + comp[:,:,:3]*alpha3_p
def doRenderAndCompose(envmap_fn, background_fn):
outfile = os.path.join(output_dir, '{}_{}.png'.format(bn(envmap_fn), bn(background_fn)))
if os.path.exists(outfile):
print('Already done: ', outfile)
return
shutil.copyfile(envmap_fn, './envmap.exr')
runBlender()
render = imread('out.png')
background = imread(background_fn)
comp = addBackground(render, background)
return comp
def main():
# Warning: Filenames should not be in ("out.png", "out_groundplane.png")
# Change filename here (for a loop maybe?)
envmap_filename = "mon_envmap.exr"
background_filename = "mon_background.png"
#render = doRenderAndCompose(envmap_filename, background_filename)
render = imread('out.png')
background = imread(background_filename)
render = addBackground(render, background)
if render is not None:
imwrite(render, os.path.join(output_dir, '{}_{}.png'.format(bn(envmap_filename), bn(background_filename))))
groundplane_fn = [x for x in os.listdir('./out_groundplane/') if x.endswith('.png')][0]
shutil.move(os.path.join('./out_groundplane/', groundplane_fn), os.path.join(output_dir, '{}_{}_groundplane.png'.format(bn(envmap_filename), bn(background_filename))))
shutil.rmtree('./out_groundplane/')
if __name__ == '__main__':
main()
This file has been truncated, but you can view the full file.
View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment