Home > database >  How do i speed up this looping of pixels in PIL
How do i speed up this looping of pixels in PIL

Time:06-22

I want to treat the r and g channel of a pixel and convert it from 0 <-> 255 to -1 <-> 1, then rotate (r, g) around (0,0) using the angle stored in rotations[i]. This is how I normally do it with regular for loops, but since the images I work with are ~4k*4k in dimensions, this takes a long time, and I would love to speed this up. I have little knowledge about parallelization, etc., but any resources would be helpful. I've tried libraries like joblib and multiprocessing, but I'm feeling as though I've made some fundamental mistake in those implementations usually resulting in some pickle error.

c = math.cos(rotations[i])
s = math.sin(rotations[i])
pixels = texture_.load()
for X in range(width):
    for Y in range(height):
        x = (pixels[X, Y][0]/255 -.5)*2
        y = (pixels[X, Y][1]/255 -.5)*2
        z = pixels[X, Y][2]
        x_ = x*c-y*s
        y_ = x*s y*c
        x_ = 255*(x_/2 .5)
        y_ = 255*(y_/2 .5)
        pixels[X, Y] = (math.floor(x_), math.floor(y_), z)

CodePudding user response:

Use numpy to vectorize the computation and compute all individual elements at once in a matrix style computation.

Try something like this:

import numpy as np

pixels = np.array(pixels)  # Assuming shape of (width, length, 3)

x = 2 * (pixels[:, :, 0]/255 - 0.5)
y = 2 * (pixels[:, :, 1]/255 - 0.5)
z = pixels[:, :, 2]
x_ = x * c - y * s
y_ = x * s   y * c
x_ = 255 * (x_ / 2   .5)
y_ = 255 * (y_ / 2   .5)
pixels[:, :, 0] = np.floor(x_)
pixels[:, :, 1] = np.floor(y_)
pixels[:, :, 2] = z
  • Related