Wednesday, 3 February 2021

Composing an arbitrarily long composition of Images in Python

Inspired by this post for composing simple functions and this post using np.mgrid to display a function; I'm attempting to compose a chain images created by various functions functions. I'm able to get the below program to generate an image for 1 variable functions, but I hope to be able to use 2 variable functions though I am unsure how to modify lambda and the input to ComposedImageArray.

from PIL import Image
from functools import reduce
import numpy as np, random

def functionArray(depth = 0):
    FunctList = []

    for x in range(depth):
        func = random.choice(functions)
        FunctList.append(func)
    return FunctList

def composite_function(*func):
    def compose(f, g):
        return lambda x: f(g(x))

    return reduce(compose, func, lambda x: x)

def XSquared(xx):
    return xx ** 2

def YSquared(yy):
    return yy ** 2

def BothXandY(xx,yy):
    return xx + yy

def SquaredXandY(xx,yy):
    return xx**2 + yy**2

width = height = 256
xx, yy = np.mgrid[:height, :width]

testing = np.ones((height, width)) * 2 #Make an array as the initial input image
functions = (XSquared,YSquared) #Possible functions to select from
# functions = (BothXandY,SquaredXandY()) - I'd like to be able to use functions of two variables
TheList = functionArray(10) #Gives a random list of functions chosen from functions.
ComposedImageArray = composite_function(*TheList) #Combines creates an image iteratively by composing each of the functions in TheList
print(TheList) #Gives a list of functions
composedImage = ComposedImageArray(testing)
# print(composedImage)
img = Image.fromarray(composedImage, 'L')# Creates an PIL image.
img.show()
img.save('Composed.png')


from Composing an arbitrarily long composition of Images in Python

No comments:

Post a Comment