Memcpy into image.pixels

Hello there,

I wrote a bit on lossy compression. So I shove a big block of packed data into my decoder, it spits out an array of floats, now how do I copy these into the pixel array for a Blender image? I know I can just read from a buffer but that’s going to take forever in python.

So I could write it in C, slap the function on a dll or whatever and call it with ctypes, then pass the image as a pointer. Yeah, sounds good to me but I’ve never really messed with as_pointer() so I don’t know the caveats. Do I just cast the address into some struct from BKE_image or what?

Flatten the array and use foreach_set. New methods in image.pixels!

Alright, that should work too. How well does it scale? I might be using this to load in several materials (say a couple hundred, average four textures each). I’d expect to see some additional overhead per image due to the decoder having to interface with python as opposed to doing the copying directly in C. Eeeh, not much testing yet, but with the low-end rig I’m stuck with I’d say it could get up to an eight to around half a second depending on size, per material. Would be nice to do faster.

Depends on where the source data is, but for objects that supports the buffer protocol, eg. numpy arrays, foreach_set is as close to memcpy you can get without going through ctypes.

Sounds like the biggest speed boost would be to access the data in memory without having it read in python. numpy.ctypeslib.as_array() can help with that, assuming you got the memory address.

In which case this might be a decent read:

1 Like

NEAT. Thank you c:

I’ll update this with some code when I have everything working properly.