Home > Back-end >  Vectorize scalar multiplication in PixelAccess in PIL
Vectorize scalar multiplication in PixelAccess in PIL

Time:06-03

I need to vectorize a scalar multiplication factor on PixelAccess object that I am currently doing in a nested for loop.

Input Image enter image description here

Current Attempt

original = Image.open('img.png')
TEMP = '/tmp/tmp.jpg'
original.save(TEMP, quality=90)
temporary = Image.open(TEMP)
diff = ImageChops.difference(original, temporary)
d = diff.load()
SCALE = 10

# Part to vectorize
WIDTH, HEIGHT = diff.size
for x in range(WIDTH):
    for y in range(HEIGHT):
        d[x, y] = tuple(k * SCALE for k in d[x, y])

Problem is the PixelAccess object is strutured in a way that it is a 2d array of 3-element tuples, which makes it unintuitive to fit into a numpy framework.

CodePudding user response:

Instead of accessing individual pixels you could use build-in image ops: your scaling by a factor of SCALE can be done as adding the image to itself with a scale factor scale = 2 / SCALE, see docs:

diff = ImageChops.add(diff, diff, 2/SCALE)

On my computer this is 95 times faster for the provided example image.
Please note that the result will be clipped to 255.

  • Related