Search code examples
pythonalphablenderrgbabpy

Reading alpha from each pixel in Blender


I seem to have a problem with reading pixel RGBA values (particularly alpha value) from a PNG image in Blender (with python).

I do the following:

for i in range(0, len(bpy.data.images["name_of_my_png"].pixels), 4):
        print(bpy.data.images["name_of_my_png"].pixels[i:i+4]);

but I never really get any expected results for each pixel it prints out the same output - 1.0, 1.0, 1.0, 0.0 (I assume those are values of R,G,B and A respectively).

I'm pretty sure that the png is loaded in blender's cache, and that it is just a regular RGBA png image with both visible and invisible parts to it, so logically my printed output should contain some variation not just 1.0, 1.0, 1.0 and 0.0 constantly for each pixel...?

Could someone point out to me at what exactly I'm doing wrong? How do I read pixel data of an image through Blender-python at all? Maybe I am using a completely wrong approach?


Solution

  • Your code is working perfectly (tested with blender 2.71).

    There are multiple possible explanations, why the output doesn't look like expected:

    • Flipped Vertically: Blender is using OpenGL internally. In OpenGL, the origin of an image is in the lower left corner of the image (with the y-axis pointing upwards), not the upper left (with the y-axis pointing downwards) as you might be already used to.
      This way, the printed area of your code is not the upper left, but more the lower left 4x4 corner of your image. Check, whether the output matches with the lower left corner of your image.
    • Transparent Pixels not saved: When saving the image-file, many image programs don't store the colors in transparent areas. You might want to create an 4x4 pixel large image with gimp, save as png file making sure to check the Save color values from transparent pixels checkbox.
    • Premultiplied alpha (not the cause for your observation): Some algorithms gain in elegance and performance when using a premultiplied color format. Instead of seperate r,g,b,a channels, the image is stored by multiplying each color channel wit the alpha channel r*a, g*a, b*a, a.