How to combine images using Python

I have a couple of images in a python script that I want to add together. Here is a rough example of what I want to do. All the image variables are of the type bpy.types.Image:

final_image = bpy.ops.image.new(name="lightmap.png", width=1024, height=1024)

#This line does not work
final_image = lightmap_direct + lightmap_indirect + lightmap_emissive

So my question is if there is an easy way to add these images together. I am mainly interested in the add blend mode, though others modes are also interesting.

• The + operator isn't overloaded to do that. What exactly would the + symbolize? Additive? or mix? It can be done using bpy alone but it's more involved than your example.. Oct 25 '15 at 12:47

Blender comes bundled with numpy. Image references have a property called .pixels which you can turn into a numpy array of the same dimensions. Numpy does use overloaded operators for array math. The initial setup aside, you'll see it is quite close to what you were trying.

import math
import numpy as np

import bpy

def np_array_from_image(img_name):
img = bpy.data.images[img_name]
return np.array(img.pixels[:])

pixelsA = np_array_from_image('A')
pixelsB = np_array_from_image('B')
pixelsC = np_array_from_image('C')
pixelsD = (pixelsA + pixelsB + pixelsC) / 3

image_D = bpy.data.images['D']
image_D.pixels = pixelsD.tolist()

# then click in the UV editor / to update the view..to see the pixels of D updated

Maybe this will give enough insight, and push towards learning some numpy.

This does 'mix' btw.. I'm not sure about the algorithm for add.. (below shown using material rgb mix nodes) it's not as simple as a+b+c. maybe something like adding the smallest value of each array:

interim_1 = np.minimum(pixelsA, pixelsB)
pixelsD = np.minimum(interim_1, pixelsC)

producing this: • Just out of interest: Why fortran is doing the math?
– p2or
Oct 25 '15 at 13:09
• I've edited the answer. It may not be executed in Fortran, most likely straight in C. Both execute much faster than Python, and are the reason numpy is chosen for fast computations using a python higher level language as a 'director'. Oct 25 '15 at 13:13
• Oct 25 '15 at 13:14
• Interesting, nice to know that numpy is a built-in module now. Thanks zeffii!
– p2or
Oct 25 '15 at 13:33
• Nice, also did not know that numpy was built in! About the "add" thing, I have three lightmaps (direct, indirect, emitted). Adding the rgb values, at least i think, should give the correct result in that case. Anyhow, good answer. Oct 25 '15 at 14:08