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 07, 2012

adjusting image pixels (walkthrough)

Experiment with small images

For example experiment along using this image (24px wide, 7px high)

Number of pixels

This shows how to get the number of pixels in an image
import bpy

D = bpy.data

test_file = 'firefly_test_pattern_2.tga'
img = D.images[test_file]

# double division symbol forces integer result.
# 'pixels' here are ungrouped, every sequence of 
# 4 consecutive items in pixels is an rgba when
# combined
print( len(img.pixels)//4)

Dimensions

This shows how to get the width and height of an image
import bpy

D = bpy.data

test_file = 'firefly_test_pattern_2.tga'
img = D.images[test_file]

#alias if you can
w = width = img.size[0]
h = height = img.size[1]

print('image width: %d' % w)
print('image height: %d' % h)

Indexing!

This shows how to extract the array of pixels into a new list, for faster access.
import bpy
D = bpy.data

test_file = 'firefly_test_pattern_2.tga'
img = D.images[test_file]

# work on a copy instead, it's much faster
pixels = list(img.pixels)

# this collects every 4 items in pixels and stores them inside a tuple
# and sticks all tuples into the grouped_list
grouped_list = [pixels[ipx:ipx+4] for ipx in range(0, len(pixels), 4)]

print(len(grouped_list))
print(grouped_list)

coordinates from pixel index and back

This shows how to extract the array of pixels into a new list, for faster access.
import bpy
D = bpy.data

test_file = 'firefly_test_pattern_2.tga'
img = D.images[test_file]
pixels = list(img.pixels)
grouped_list = [pixels[ipx:ipx+4] for ipx in range(0, len(pixels), 4)]

some convenience functions

contrast and compare the above, with the following slightly more convenient ways to name objects. Some objects deserve short names. and