diff options
author | Élie Michel <elie> | 2021-03-29 13:04:42 +0300 |
---|---|---|
committer | Jacques Lucke <jacques@blender.org> | 2021-03-29 13:08:41 +0300 |
commit | ae9d61e7fea25535803e92298f44b184c9190f76 (patch) | |
tree | c00df281423f58548009c3e434a2cb65fc975aa1 /release/scripts/templates_py | |
parent | 075a19049fd14fa33eaf731b25db06b3dee2a517 (diff) |
Python API: add template for image processing
Since a few releases it is possible to process Blenders images much
more effficiently than before thanks to the `foreach_get`/`foreach_set`
methods. This new template shows how those methods can be used together
with numpy.
Differential Revision: https://developer.blender.org/D9400
Diffstat (limited to 'release/scripts/templates_py')
-rw-r--r-- | release/scripts/templates_py/image_processing.py | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/release/scripts/templates_py/image_processing.py b/release/scripts/templates_py/image_processing.py new file mode 100644 index 00000000000..2392faf440c --- /dev/null +++ b/release/scripts/templates_py/image_processing.py @@ -0,0 +1,35 @@ +# This sample shows the an efficient way of doing image processing +# over Blender's images using Python. + +import bpy +import numpy as np + + +input_image_name = "Image" +output_image_name = "NewImage" + +# Retrieve input image. +input_image = bpy.data.images[input_image_name] +w, h = input_image.size + +# Allocate a numpy array to manipulate pixel data. +pixel_data = np.zeros((w, h, 4), 'f') + +# Fast copy of pixel data from bpy.data to numpy array. +input_image.pixels.foreach_get(pixel_data.ravel()) + +# Do whatever image processing you want using numpy here: +# Example 1: Inverse red green and blue channels. +pixel_data[:,:,:3] = 1.0 - pixel_data[:,:,:3] +# Example 2: Change gamma on the red channel. +pixel_data[:,:,0] = np.power(pixel_data[:,:,0], 1.5) + +# Create output image. +if output_image_name in bpy.data.images: + output_image = bpy.data.images[output_image_name] +else: + output_image = bpy.data.images.new(output_image_name, width=w, height=h) + +# Copy of pixel data from numpy array back to the output image. +output_image.pixels.foreach_set(pixel_data.ravel()) +output_image.update() |