Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

August 17, 2012

Faster Pixel manipulation inside blender

Storing a pixel lookuptable in a dict, although unordered, is probably faster for lookup and manipulation. How true is this? Well, throw some sample images at it and timeit() compared to some other structures.
px_list = [ 
    1, 2, 3, 4, 5, 6, 7, 8,
    9, 10,11,12,13,14,15,16,
    17,18,19,20,21,22,23,24,
    25,26,27,28,29,30,31,32]



def idx_to_co(idx, width):
    r = int(idx / width)
    c = idx % width
    return r, c

def px_list_to_dict(px_list, width):
    px_dict = {}
    for idx, px in enumerate(px_list):
        px_dict[idx_to_co(idx, width)] = px

    return px_dict

image_width = 8
px_dict = px_list_to_dict(px_list, image_width)

# unordered, but much faster lookup than list
for i in px_dict:
    print(i)

import bpy

D = bpy.data
img = D.images['moop2.png']

img_width = img.size[0]
img_height = img.size[1]

# slowest part is the transfer from pixel array to list
pxs = list(img.pixels)

num_values = len(pxs)
px_list = [pxs[i:i+4] for i in range(num_values)[::4]]


def idx_to_co(idx, width):  
    r = int(idx / width)  
    c = idx % width  
    return r, c  


def px_list_to_dict(px_list, width):
    px_dict = {}
    for idx, px in enumerate(px_list):
        px_dict[idx_to_co(idx, width)] = px

    return px_dict


px_dict = px_list_to_dict(px_list, img_width)

print(px_dict[(30,30)])
How about using tuple for lookup? ..still have to time this, but it looks interesting, it has to be faster in some way because it is an immutable structure.
import bpy
D = bpy.data
img = D.images['moop2.png']
img_width = img.size[0]
img_height = img.size[1]
# slowest part is the transfer from pixel array to list
pxs = tuple(img.pixels)
r,g,b,a = pxs[::4], pxs[1::4], pxs[2::4], pxs[3::4]
px_list = zip(r,g,b,a)
def idx_to_co(idx, width):
r = int(idx / width)
c = idx % width
return r, c
def px_list_to_dict(px_list, width):
px_dict = {}
for idx, px in enumerate(px_list):
px_dict[idx_to_co(idx, width)] = px
return px_dict
px_dict = px_list_to_dict(px_list, img_width)
print(px_dict[(30,30)])
view raw tuple_test.py hosted with ❤ by GitHub