Title: Spiralize an image in Python
My post Rainbowize an image in Python shows how to shade an image in strips with different color tones. This example does something similar except the color tones are arranged in a spiral.
This example combines techniques from these posts:
See the first one for information about giving images different color tones. See the second for information about generating points that define the sections of a spiral. Once you know how to do those two things, all that's left is actually spiralizing the image.
Spiralizing Images
The basic approach is to repeatedly colorize the image and then paste the result onto the final output image using a spiral-shaped mask. Here's the spiralize_image function that does the work.
def spiralize_image(image, colors):
'''Spiralize the image.'''
# Each color entry is r, g, b, brightness all between 0.0 and 1.0.
result = image.copy()
# Generate spiral polygons.
rect = (0, 0, result.width-1, result.height-1)
cx = result.width / 2
cy = result.height / 2
A = 100
num_colors = len(colors)
num_spirals = num_colors
polygons = get_spiral_polygons(rect, cx, cy, num_spirals, A)
# Process the spirals.
for i, color in enumerate(colors):
# Make the mask.
mask = Image.new('L', image.size, color='black')
dr = ImageDraw.Draw(mask)
dr.polygon(polygons[i], fill='white')
# Colorize the image.
r, g, b, brightness = color
colorized_image = PointOps.to_color_tone(image, r, g, b, brightness)
# Paste with the mask.
result.paste(colorized_image, (0, 0), mask)
return result
The function first copies the input image so it doesn't mess up the original. Then, after setting a few parameters, it calls get_spiral_polygons to get polygons representing the pieces of the spiral. See Draw filled Archimedes spirals in Python for information about that function.
Next the code loops through the colors. For each color, it uses the corresponding spiral polygon to create a mask image. It creates the new mask, initially setting all of its pixels to black. It then fills the current spiral polygon with white. The result is a mask that is all black except within the current spiral polygon where it is white.
The function then colorizes the image using the current color tone. (See Use a color matrix to set an image's color tone in Python.) It then pastes the colorized image onto the result image using the spiral mask so only those pixels that correspond to white pixels in the mask are copied.
The rest of the program does all of the usual things like letting you load an image, sizing the image to fit the program's canvas, saving results, etc.
Conclusion
The spiralize_image function does all of the new work. Download the example to experiment with it. For example, you could change the colors or the parameter A used to generate the spirals.
|