3

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

How can I do this in Blender?

unfa
  • 1,199
  • 15
  • 23

1 Answers1

11
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

unfa
  • 1,199
  • 15
  • 23
  • 2
    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[:] – Mr.Epic Fail Sep 13 '19 at 09:00
  • For some reason, this doesn't work for me... It doesn't crash, but all pixel values are 0.0... – Thomas Harris Mar 24 '21 at 15:27
  • @ThomasHarris may be it's because of the blender version? This question is from 3 years ago and Blender python API changed a lot since then. – mqbaka mqbaka Jan 05 '22 at 05:25
  • works for me, indeed local data goes way faster – Phil Apr 25 '23 at 04:56