Open
Description
Question
I have a list of RGB tuples. I want to make it Oklab and make a linear gradient with it, then turn it into an RGB Pillow Image. Regular code for RGB looks like this. Please critique also, it's supposed to be as fast as it can be.
def create_linear_gradient(width, height, stops, direction):
# stops is a list { percent, (r, g, b) }
# Normalize the direction vector
dx, dy = direction
magnitude = (dx ** 2 + dy ** 2) ** 0.5
dx /= magnitude
dy /= magnitude
# create coordinate grids
x = np.linspace(0, 1, width)
y = np.linspace(0, 1, height)
xv, yv = np.meshgrid(x, y)
# Compute the distance map and center it
distance_map = (xv - 0.5) * dx + (yv - 0.5) * dy
distance_map = distance_map - distance_map.min()
distance_map = distance_map / distance_map.max() # Normalize to [0, 1]
# Sort and interpolate stops
stops = sorted(stops, key=lambda stop: stop[1])
stop_colors, stop_positions = zip(*stops)
# Convert to arrays for interpolation
stop_positions = np.array(stop_positions)
stop_colors = np.array(stop_colors, dtype=np.float32)
# Interpolate each color channel
r_channel = np.interp(distance_map, stop_positions, stop_colors[:, 0])
g_channel = np.interp(distance_map, stop_positions, stop_colors[:, 1])
b_channel = np.interp(distance_map, stop_positions, stop_colors[:, 2])
gradient = np.stack([r_channel, g_channel, b_channel], axis=-1).astype(np.uint8)
return Image.fromarray(gradient)
Activity