I'm trying to open an image stored internally in Blender into the Image module from Pillow (https://pillow.readthedocs.io/en/3.1.x/reference/Image.html). This should be a simple operation but I'm having some problems with it. I don't want to use the path of the image, but I want to work with the pixels.

from bpy import data
from PIL import Image
import numpy as np
# Generate a random image
width = 80
height = 40
img = data.images.new('random_colors', width=width, height=height)
num_pixels = len(img.pixels)
from random import random as rnd
#Create random colors for each pixel
for px in range(0, num_pixels-5, 12):
    r = rnd()
    b = rnd()
    g = rnd()
    a = 1
    cols = (r, g, b, a)
    for i in range(4):
        img.pixels[px+i] = cols[i]
pxs = bytearray(int(p*255) for p in img.pixels)
image = Image.fromarray(np.array(pxs), 'RGBA')

I'm getting : IndexError: tuple index out of range

Any hint?


I'm not immediately able to test the numpy and PIL lines as I don't have those installed, but...

screenshot of Blender script editor showing image data from user's script

First - is your main loop really setting the pixels you intended? The comment says "create random colors for each pixel" but what it's actually doing is creating random colors in every 3rd pixel - and the stop condition of num_pixels-5 is arbitrary and seemingly will have no effect, since you're stepping 12 each time.

So that's the first thing. If you actually want to set all pixels, it would be range(0, num_pixels, 4)

Second - your line creating the 'pxs' array is making an int array of length 12800 (80*40*4) out of all the pixel components. If you want a binary packed representation, maybe you need to do

pxdata = struct.pack("<%uf" % len(img.pixels), *img.pixels) # pack RGBA floats as binary.

instead? Double-check what the PIL Image call is taking.

| improve this answer | |
  • $\begingroup$ Regarding the comment "random colour for each pixel" you are right, that's misleading. I actually wanted it to be a sort of checkboard. The suggestion is correct! Thanks! $\endgroup$ – Rage Aug 29 '19 at 18:16

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.