shapevolve package¶
Submodules¶
shapevolve.adjusters module¶
Adjusters that modify the source image during evolution, but are undone for the final product.
-
shapevolve.adjusters.
strong_dark_adjust
(original_image)[source]¶ A function that applies a strong brightening filter to a dark image.
- Parameters
original_image (ndarray) – The original image.
- Returns
The image with the adjustment applied.
- Return type
ndarray
-
shapevolve.adjusters.
strong_dark_unadjust
(adjusted_image)[source]¶ A function that reverses a strong brightening filter to a dark image.
- Parameters
adjusted_image (ndarray) – The original image.
- Returns
The image with the adjustment applied.
- Return type
ndarray
shapevolve.callbacks module¶
Callbacks that can be given to the Evolver class, to be run when a successful change is applied to the genome.
-
class
shapevolve.callbacks.
CSVLogger
(csv_filepath, frequency=1)[source]¶ Bases:
object
A class that defines callbacks which record statistics into a CSV file.
A constructor for the class that stores a path to a CSV file.
- Parameters
csv_filepath (str) – The filepath of the CSV file that statistics will be written to.
frequency (int) – The frequency at which stats will be saved.
-
callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ A callback that stores offspring, generation, loop index, and error into the class’s CSV file.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
class
shapevolve.callbacks.
GenomeSaver
(genome_root, frequency=1)[source]¶ Bases:
object
A class that defines a callback where genomes are saved to files.
Constructs a genome saver class that takes a given root file path.
- Parameters
genome_root (str) – The file path where genomes should be saved.
frequency (int) – The frequency at which files will be saved.
-
callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ A callback that saves genomes to a filepath.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
class
shapevolve.callbacks.
HighQualityImageSaver
(image_root, frequency=1)[source]¶ Bases:
shapevolve.callbacks.ImageSaver
A subclass of ImageSaver that scales images to the original resolution before saving them.
A constructor for the class that defines a root filepath for saved images.
- Parameters
image_root (str) – The root filepath for saved images.
frequency (int) – The frequency at which files will be saved.
-
callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ A callback that scales an image before providing it to the equivalent method in ImageSaver.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
class
shapevolve.callbacks.
ImageSaver
(image_root, frequency=1)[source]¶ Bases:
object
A class that defines a callback where images built during evolution are saved.
A constructor for the class that defines a root filepath for saved images.
- Parameters
image_root (str) – The root filepath for saved images.
frequency (int) – The frequency at which files will be saved.
-
callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ A callback that saves the best image so far into a png file.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
class
shapevolve.callbacks.
MatplotImageSaver
(image_root, frequency=1)[source]¶ Bases:
shapevolve.callbacks.ImageSaver
A class that defines a callback where images shown by matplotlib during evolution are saved. Must be used with a variant of visual_callback in the same list.
A constructor for the class that defines a root filepath for saved images.
- Parameters
image_root (str) – The root filepath for saved images.
frequency (int) – The frequency at which files will be saved.
-
callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ A callback that saves the best image so far into a png file.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
shapevolve.callbacks.
default_callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ The default callback that the Evolver class uses. Currently visual_callback.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
shapevolve.callbacks.
quiet_verbose_callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ The same thing as verbose_callback, but this only runs every 50 generations.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
shapevolve.callbacks.
quiet_visual_callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ The same thing as visual_callback, but this only runs every 50 generations.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
shapevolve.callbacks.
verbose_callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ A callback that prints the status of the evolution into standard output.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
-
shapevolve.callbacks.
visual_callback
(offspring, changes, loop_index, num_mutation_type_switches, error, complex_mutation, best_image, genome)[source]¶ A simple callback that uses matplotlib to provide a live update of the image on the screen.
- Parameters
offspring (int) – The total number of offspring already processed.
changes (int) – The total number of changes already applied to the genome.
loop_index (int) – The total number of loops already performed.
num_mutation_type_switches (int) – The total number of switches between simple and complex mutations so far.
error (float) – The error of the current genome compared to the base image.
complex_mutation (bool) – Whether complex mutations are being applied or not.
best_image (ndarray) – The best image so far.
genome (Genome) – The genome for the best image so far.
shapevolve.drawers module¶
Defines functions that can be used to draw shapes on an image based on genetic information by the evolver class.
-
shapevolve.drawers.
add_circle
(image, gene, palette)[source]¶ Adds a circle to an image based on info from a gene.
- Parameters
image (ndarray) – The base image to draw the circle on.
gene (Gene) – The gene that specifies how to draw the circle.
palette (List[Tuple[int, int, int]]) – The color palette where colors are referenced from.
-
shapevolve.drawers.
add_square
(image, gene, palette)[source]¶ Adds a square to an image based on info from a gene.
- Parameters
image (ndarray) – The base image to draw the square on.
gene (Gene) – The gene that specifies how to draw the square.
palette (List[Tuple[int, int, int]]) – The color palette where colors are referenced from.
shapevolve.error_metrics module¶
Defines error metrics that can be used to evaluate similarity between two images.
-
shapevolve.error_metrics.
mean_squared_error
(image, source)[source]¶ Calculates the mean squared error between two images.
- Parameters
image (ndarray) – The constructed image.
source (ndarray) – The original image.
- Returns
The mean squared error between the two images.
- Return type
float
-
shapevolve.error_metrics.
structural_similarity_error
(image, source)[source]¶ Calculates the opposite of the structural similarity between two images.
- Parameters
image (ndarray) – The constructed image.
source (ndarray) – The original image.
- Returns
The opposite of the structural similarity between the two images.
- Return type
float
shapevolve.evolver module¶
A class that manages evolving a genome based on certain specifications.
-
class
shapevolve.evolver.
Evolver
(base_image, saved_genome=None, num_shapes=1000, num_colors=256, target_resolution=250, adjusters=None, preprocesses=None, draw=<function add_circle>, calculate_error=<function mean_squared_error>)[source]¶ Bases:
object
A class that manages evolving a genome based on certain specifications.
A constructor that specifies base images, a saved genome, and settings for the evolution.
- Parameters
base_image (Image) – The source PIL image object that the evolution will be performed against.
saved_genome (Genome) – An optional saved genome. If unspecified, a genome will be randomly generated.
num_shapes (int) – The number of shapes to be used in the genome construction.
num_colors (int) – The number of colors that should be used by the shapes.
target_resolution (int) – The resolution that images will be resized to during the evolution.
adjusters (List[Dict[str, Callable]]) – A list of reversible adjusters that can be applied during the evolution. See adjusters module.
preprocesses (List[Callable]) – A list of preprocessors that will be applied to the image before the evolution. See preprocessors module.
draw (Callable) – The function used to draw shapes on the image. See drawers module.
calculate_error (Callable) – The function used to calculate errors between images. See error_metrics module.
-
evolve
(num_generations=5000, callbacks=None, silent=False)[source]¶ Evolves a genome, and returns it after evolution.
- Parameters
num_generations (int) – The number of generations to evolve to. Note: early stoppages are possible.
callbacks (List[Callable]) – Callbacks that can be run when a new generation is evolved.
silent (bool) – Whether callbacks will be run at all.
- Returns
Genome
shapevolve.gene module¶
A Gene class that defines the properties of a single shape on an image.
-
class
shapevolve.gene.
Gene
(max_radius, min_radius, height, width, num_colors, radius=None, center=None, color=None, alpha=None)[source]¶ Bases:
object
A Gene class that defines the properties of a single shape on an image.
Constructs a gene and its initial properties.
- Parameters
max_radius (int) – The maximum possible radius the gene can have.
min_radius (int) – The minimum possible radius the gene can have.
height (int) – The height of the image that the gene is drawing on.
width (int) – The width of the image that the gene is drawing on.
num_colors (int) – The number of colours the gene can have.
radius (int) – The current radius of the gene.
center (Tuple[int, int]) – The coordinates of the center of the gene’s shape.
color (int) – The current color of the gene, as an index of an external color palette list.
alpha (float) – The current opacity of the gene, between 0 and 1.
-
completely_randomize
(initialization=False)[source]¶ Completely randomizes the properties of the gene.
- Parameters
initialization (bool) – Whether this is being called from the constructor.
-
get_scaled_version
(ratio, fill_gaps)[source]¶ Creates a scaled version of the gene, according to some ratio (original dimension / scaled dimension)
- Parameters
ratio – (original dimension) / (scaled dimension)
fill_gaps – Whether the radii should be slightly expanded so gaps don’t form between shapes.
- Returns
The scaled gene.
- Return type
-
shapevolve.gene.
random
() → x in the interval [0, 1).¶
shapevolve.genome module¶
The Genome class represents a shape sequence and its various properties, from which an image can be built.
-
class
shapevolve.genome.
Genome
(sequence, ratio, height, width, background_color, adjusters, palette, draw)[source]¶ Bases:
object
This class represents a shape sequence and its various properties, from which an image can be built.
Constructs a genome based on certain properties.
- Parameters
sequence (List[Gene]) – A sequence of Gene objects that represent the shapes in the image.
ratio (float) – The ratio between the evolution image dimensions and the original image dimensions.
height (int) – The height of the image.
width (int) – The width of the image.
background_color (Tuple[int, int, int]) – The background color of the image.
adjusters (List[Dict[str, Callable]]) – Reversible image adjusters that can be applied and unapplied to the image.
palette (List[Tuple[int, int, int]]) – A list of RGB color tuples that colors are referenced from.
draw (Callable) – A function that is used to draw an image according to a Gene object.
-
render_image
(height, width, sequence, after_unadjustment)[source]¶ Renders an image according to certain parameters.
- Parameters
height (int) – The height of the desired image.
width (int) – The width of the desired image.
sequence (List[Gene]) – The gene sequence to draw on the image.
after_unadjustment (bool) – Whether the image has already been un-adjusted.
- Returns
The rendered image.
- Return type
ndarray
-
render_raw_image
(after_unadjustment=False)[source]¶ Renders the image without any scaling.
- Parameters
after_unadjustment (bool) – Whether the image has already been un-adjusted.
- Returns
The rendered image.
- Return type
ndarray
-
render_scaled_image
(after_unadjustment=False, fill_gaps=True)[source]¶ Renders a scaled version of an image according to the genome’s ratio field.
- Parameters
after_unadjustment (bool) – Whether the image has already been un-adjusted.
fill_gaps (bool) – Whether gaps should be filled in the scaled image.
- Returns
The scaled image.
- Return type
ndarray
-
exception
shapevolve.genome.
MismatchedGenomeError
[source]¶ Bases:
Exception
An error that occurs when two genomes do not share the same properties with one another.
shapevolve.main module¶
The main CLI interface for the standalone app.
-
shapevolve.main.
imwrite
(filename, img[, params]) → retval¶ . @brief Saves an image to a specified file. . . The function imwrite saves the image to the specified file. The image format is chosen based on the . filename extension (see cv::imread for the list of extensions). In general, only 8-bit . single-channel or 3-channel (with ‘BGR’ channel order) images . can be saved using this function, with these exceptions: . . - 16-bit unsigned (CV_16U) images can be saved in the case of PNG, JPEG 2000, and TIFF formats . - 32-bit float (CV_32F) images can be saved in PFM, TIFF, OpenEXR, and Radiance HDR formats; . 3-channel (CV_32FC3) TIFF images will be saved using the LogLuv high dynamic range encoding . (4 bytes per pixel) . - PNG images with an alpha channel can be saved using this function. To do this, create . 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels . should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below). . . If the format, depth or channel order is different, use . Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O . functions to save the image to XML or YAML format. . . The sample below shows how to create a BGRA image and save it to a PNG file. It also demonstrates how to set custom . compression parameters: . @include snippets/imgcodecs_imwrite.cpp . @param filename Name of the file. . @param img Image to be saved. . @param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, … .) see cv::ImwriteFlags
shapevolve.mutations module¶
Defines mutations.
-
shapevolve.mutations.
complex_mutation
(ancestor_image, base_image, sequence, num_shapes, calculate_error, palette, draw)[source]¶ Computes the effects of a complex mutation.
- Parameters
ancestor_image (ndarray) – An image with the solid background color only.
base_image (ndarray) – The original image for comparison.
sequence (List[Gene]) – The existing gene sequence.
num_shapes (int) – The number of shapes to draw.
calculate_error (Callable) – The error metric method.
palette (List[Tuple[int, int, int]]) – The color palette to use.
draw (Callable) – The method to draw the shape according to the gene.
- Returns
The error, the mutated gene, the new image, the index of the mutated gene, whether mutated gene was placed on top.
- Return type
Tuple[float, Gene, ndarray, int, bool]
-
shapevolve.mutations.
random
() → x in the interval [0, 1).¶
-
shapevolve.mutations.
simple_mutation
(image, base_image, sequence, calculate_error, palette, draw)[source]¶ Computes the effects of a simple mutation.
- Parameters
image (ndarray) – The image to draw the gene on.
base_image (ndarray) – The original image to compare to.
sequence (List[Gene]) – The gene sequence.
calculate_error (Callable) – The error metric method.
palette (List[Tuple[int, int, int]]) – The color palette to use.
draw (Callable) – The method to draw the shape according to the gene.
- Returns
The error, the mutated gene, and the new image.
- Return type
Tuple[float, Gene, ndarray]
shapevolve.preprocessors module¶
-
shapevolve.preprocessors.
brighten_preprocess
(image)[source]¶ Increases brightness of an image.
- Parameters
image (Image) – The image to process.
- Returns
The processed image.
- Return type
Image
-
shapevolve.preprocessors.
contrast_preprocess
(image)[source]¶ Increases contrast of an image.
- Parameters
image (Image) – The image to process.
- Returns
The processed image.
- Return type
Image
-
shapevolve.preprocessors.
debrighten_preprocess
(image)[source]¶ Decreases brightness of an image.
- Parameters
image (Image) – The image to process.
- Returns
The processed image.
- Return type
Image
-
shapevolve.preprocessors.
decontrast_preprocess
(image)[source]¶ Decreases contrast of an image.
- Parameters
image (Image) – The image to process.
- Returns
The processed image.
- Return type
Image
-
shapevolve.preprocessors.
desaturate_preprocess
(image)[source]¶ Desaturates an image.
- Parameters
image (Image) – The image to desaturate.
- Returns
The desaturated image.
- Return type
Image
shapevolve.samples module¶
Some sample methods to show the functionality of the module.
-
shapevolve.samples.
adjustment_sample
(filepath)[source]¶ A sample function that illustrates how to use adjusters.
- Parameters
filepath (str) – The absolute filepath of an input image.
- Returns
The evolved genome.
- Return type
-
shapevolve.samples.
callback_sample
(filepath_source, filepath_csv)[source]¶ A sample function that illustrates how to add callbacks to the evolve method.
- Parameters
filepath_source (str) – The absolute filepath of an input image.
filepath_csv (str) – The filepath to save CSV statistics to.
- Returns
The evolved genome.
- Return type
-
shapevolve.samples.
draw_shape_sample
(filepath)[source]¶ A sample function that illustrates how to use custom shape drawing methods.
- Parameters
filepath (str) – The absolute filepath of an input image.
- Returns
The evolved genome.
- Return type
-
shapevolve.samples.
error_metric_sample
(filepath)[source]¶ A sample function that illustrates how to use custom error metrics.
- Parameters
filepath (str) – The absolute filepath of an input image.
- Returns
The evolved genome.
- Return type
-
shapevolve.samples.
load_genome_sample
(filepath_source, filepath_genome)[source]¶ A sample function that illustrates how to load previously saved genomes.
- Parameters
filepath_source (str) – The absolute filepath of an input image.
filepath_genome (str) – The filepath to load the pre-evolved genome.
- Returns
The evolved genome.
- Return type
-
shapevolve.samples.
preprocess_sample
(filepath)[source]¶ A sample function that illustrates how to use preprocesses.
- Parameters
filepath (str) – The absolute filepath of an input image.
- Returns
The evolved genome.
- Return type
-
shapevolve.samples.
save_genome_sample
(filepath_source, filepath_to_save_to)[source]¶ A sample function that illustrates how to save genomes.
- Parameters
filepath_source (str) – The absolute filepath of an input image.
filepath_to_save_to (str) – The filepath to save the genome.
- Returns
The evolved genome.
- Return type
-
shapevolve.samples.
save_image_sample
(filepath_source, filepath_to_save_to)[source]¶ A sample function that illustrates how to save images from genomes.
- Parameters
filepath_source (str) – The absolute filepath of an input image.
filepath_to_save_to (str) – The filepath to save the evolved image to.
- Returns
The evolved genome.
- Return type
shapevolve.utils module¶
Utility methods.
-
class
shapevolve.utils.
ColorThiefFromImage
(image)[source]¶ Bases:
colorthief.ColorThief
This class extends ColorThief to support providing images as-is instead of filenames.
Builds the ColorThief object with an image field.
- Parameters
image (Image) – The image to build colors from.
-
shapevolve.utils.
adjust
(original_image, adjusters)[source]¶ Adjusts an image based on adjusters.
- Parameters
original_image (ndarray) – The original image before adjustments.
adjusters (List[Dict[str, Callable]]) – Adjusters to apply.
- Returns
The adjusted image.
- Return type
ndarray
-
shapevolve.utils.
convert_RGB_to_BGR
(color)[source]¶ Converts a RGB color to a BGR color.
- Parameters
color (Tuple[int, int, int]) – The RGB color.
- Returns
The corresponding BGR color.
- Return type
Tuple[int, int, int]
-
shapevolve.utils.
get_image
(path)[source]¶ A shortcut to get an image from a filepath.
- Parameters
path (str) – The filepath of the image.
- Returns
The image object.
- Return type
Image
-
shapevolve.utils.
get_image_path
(name, directory)[source]¶ Gets the path of an image based on a directory in the script’s folder and a name.
- Parameters
name (str) – The name of the image.
directory (str) – The directory name, in the same folder as this script.
- Returns
The filepath.
- Return type
string
-
shapevolve.utils.
get_rescale_ratio
(image, target)[source]¶ Gets the required ratio to rescale an image to a target resolution
- Parameters
image (Image) – An image to resize.
target (int) – The target resolution to resize to.
- Returns
The min of the ratio between the target resolution and the image’s smallest dimension, and 1.
- Return type
float
-
shapevolve.utils.
show_image
(image, generation, display=None, adjusters=None)[source]¶ Uses matplotlib to show an image.
- Parameters
image (ndarray) – The image to show.
generation (int) – What generation the image corresponds to.
display (AxesImage) – The window the image should display on.
adjusters (Dict[str, Callable]) – Any adjusters that should be reversed for the image.
- Returns
The window where the image was displayed.
- Return type
AxesImage
Module contents¶
Shapevolve: A genetic algorithm to recreate artworks using simple shapes, with Python 3.