0
$\begingroup$

My Python script needs to read RGBA values from a specific pixel of a texture bitmap.

How can I do this in Blender?

$\endgroup$
4
$\begingroup$
import bpy

D = bpy.data

image_file = 'Image.png' # this refers to an image file loaded into Blender

img = D.images[image_file]

# we need to know the image dimensions
width = img.size[0]
height = img.size[1]

print ( "Image size: ", width, " x ", height )

# define location of the target pixel we want to read
target = [150, 33] # X, Y
print ("Target vector: ", target)

# target.Y * image width + target.X * 4 (as the table Pixels contains separate RGBA values)
index = ( target[1] * width + target[0] ) * 4
print ("Field index: ", index)

# aggregate the read pixel values into a nice array
pixel = [
    img.pixels[index], # RED
    img.pixels[index + 1], # GREEN
    img.pixels[index + 2], # BLUE
    img.pixels[index + 3] # ALPHA
]

# print the values for debug
print ("R: ", pixel[0])
print ("G: ", pixel[1])
print ("B: ", pixel[2])
print ("A: ", pixel[3])

I wrote this based on articles from this blog: http://blenderscripting.blogspot.com/2012/08/adjusting-image-pixels-internally-in.html

$\endgroup$
  • $\begingroup$ I found that working on a local copy of the pixels results in a huge performance improvement, if you want to write many pixels. Just use local_pixels = list(img.pixels[:]) and local_pixels[index]=red_value and img.pixels = local_pixels[:] $\endgroup$ – Mr.Epic Fail Sep 13 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.