diff --git a/README.md b/README.md index 25153f3..ed822d9 100644 --- a/README.md +++ b/README.md @@ -58,10 +58,10 @@ e = evolution.Evolution((64, 64), target, genes=256) e.evolve(max_generation=50000) -helpers.show_image(e.specie.phenotype) +e.specie.show_img() np.savetxt("Checkpoint.txt", e.specie.genotype) -cv2.imwrite("OuputImage.jpg", e.specie.phenotype) +e.specie.save_img("OutputImage.jpg") ``` # Contributing @@ -74,3 +74,6 @@ Ahmed Khalf Guilherme de Amorim [guimorg](http://github.com/guimorg) + +Tan Nian Wei +[tnwei](http://github.com/tnwei) diff --git a/circle_evolution/__init__.py b/circle_evolution/__init__.py index 11fb060..174cb10 100644 --- a/circle_evolution/__init__.py +++ b/circle_evolution/__init__.py @@ -58,13 +58,16 @@ e.evolve(max_generation=50000) # Show evolved phenotype -helpers.show_image(e.specie.phenotype) +e.specie.show_img() # Saves genotype to checkpoint np.savetxt("Checkpoint.txt", e.specie.genotype) # Saves phenotype -cv2.imwrite("OuputImage.jpg", e.specie.phenotype) +e.specie.save_img("OutputImage.jpg") + +# Saves phenotype, resized +e.specie.save_img("OutputImage128x128.jpg", (128, 128)) ``` Here is how to load and train further from a saved checkpoint. @@ -89,7 +92,7 @@ e.evolve(max_generation=50000) # Show evolved phenotype -helpers.show_image(e.specie.phenotype) +e.specie.show_img() ``` # Contributing diff --git a/circle_evolution/helpers.py b/circle_evolution/helpers.py index 8a328d4..2b2e3ff 100644 --- a/circle_evolution/helpers.py +++ b/circle_evolution/helpers.py @@ -1,11 +1,7 @@ """Helper Functions""" import os - import cv2 -import matplotlib.pyplot as plt - - def load_target_image(image_path, color=True, size=None): """Loads images from image path. @@ -39,15 +35,3 @@ def load_target_image(image_path, color=True, size=None): # Only resizes image if it is needed! target = cv2.resize(src=target, dsize=size, interpolation=cv2.INTER_AREA) return target - - -def show_image(img_arr): - """Displays image on window. - - Arguments: - img_arr (numpy.ndarray): image array to be displayed - """ - plt.figure() - plt.axis("off") - plt.imshow(img_arr / 255) - plt.show() diff --git a/circle_evolution/main.py b/circle_evolution/main.py index 7101c92..01999fd 100644 --- a/circle_evolution/main.py +++ b/circle_evolution/main.py @@ -29,7 +29,7 @@ def main(): evolution.evolve(max_generation=args.max_generations) evolution.specie.render() - helpers.show_image(evolution.specie.phenotype) + evolution.specie.show_img() output_path_checkpoint = "checkpoint-{}.txt".format(evolution.generation) np.savetxt(output_path_checkpoint, evolution.specie.genotype) diff --git a/circle_evolution/species.py b/circle_evolution/species.py index 567041b..b85a84a 100644 --- a/circle_evolution/species.py +++ b/circle_evolution/species.py @@ -5,7 +5,7 @@ """ import cv2 - +from PIL import Image import numpy as np @@ -87,3 +87,37 @@ def load_checkpoint(self, fname, text=False): self.genotype = np.loadtxt(fname) else: self.genotype = np.load(fname) + + def show_img(self, resolution=None): + """ + Displays image of phenotype. + + Args: + resolution (tuple): (height, width) of target image. + If None, uses target image resolution. Defaults to None. + """ + im = Image.fromarray(self.phenotype.astype("uint8")) + + if resolution is None: + im.show() + else: + im_resized = im.resize(resolution) + im_resized.show() + + def save_img(self, fname, resolution=None): + """ + Saves image of phenotype. + + Args: + fname (string): Filename to save the image to. Includes format postfix, e.g. `jpg` or `png`. + resolution (tuple): (height, width) of target image. + If None, uses target image resolution. Defaults to None. + """ + im = Image.fromarray(self.phenotype.astype("uint8")) + + if resolution is None: + im.save(fname) + else: + im_resized = im.resize(resolution) + im_resized.save(fname) + diff --git a/docs/evolution.html b/docs/evolution.html index d095175..e358ab7 100644 --- a/docs/evolution.html +++ b/docs/evolution.html @@ -3,15 +3,17 @@ - + circle_evolution.evolution API documentation - - - - + + + + + +
@@ -43,22 +45,21 @@

Module circle_evolution.evolution

a target image. Attributes: - size (tuple): tuple containing height and width of target image (h, w). + size (tuple): tuple containing np.shape of target image. target (np.ndarray): target image for evolution. genes (int): the amount of circle to train the target image on. generation (int): amount of generations Evolution class has trained. specie (species.Specie): the Specie that is getting trained. """ - def __init__(self, size, target, genes=5): + def __init__(self, target, genes=100): """Initializes Evolution class. Args: - size (tuple): tuple containing height and width of target image (h, w). target (np.ndarray): target image for evolution. genes (int): the amount of circle to train the target image on. """ - self.size = size # Tuple (y, x) + self.size = target.shape self.target = target # Target Image self.generation = 1 self.genes = genes @@ -78,16 +79,16 @@

Module circle_evolution.evolution

# Randomization for Evolution y = random.randint(0, self.genes - 1) - change = random.randint(0, 6) + change = random.randint(0, new_specie.genotype_width + 1) - if change >= 6: + if change >= new_specie.genotype_width + 1: change -= 1 i, j = y, random.randint(0, self.genes - 1) i, j, s = (i, j, -1) if i < j else (j, i, 1) new_specie.genotype[i : j + 1] = np.roll(new_specie.genotype[i : j + 1], shift=s, axis=0) y = j - selection = np.random.choice(5, size=change, replace=False) + selection = np.random.choice(new_specie.genotype_width, size=change, replace=False) if random.random() < 0.25: new_specie.genotype[y, selection] = np.random.rand(len(selection)) @@ -143,7 +144,7 @@

Classes

class Evolution -(size, target, genes=5) +(target, genes=100)

Logic for a Species Evolution.

@@ -152,7 +153,7 @@

Classes

Attributes

size : tuple
-
tuple containing height and width of target image (h, w).
+
tuple containing np.shape of target image.
target : np.ndarray
target image for evolution.
genes : int
@@ -165,8 +166,6 @@

Attributes

Initializes Evolution class.

Args

-
size : tuple
-
tuple containing height and width of target image (h, w).
target : np.ndarray
target image for evolution.
genes : int
@@ -183,22 +182,21 @@

Args

a target image. Attributes: - size (tuple): tuple containing height and width of target image (h, w). + size (tuple): tuple containing np.shape of target image. target (np.ndarray): target image for evolution. genes (int): the amount of circle to train the target image on. generation (int): amount of generations Evolution class has trained. specie (species.Specie): the Specie that is getting trained. """ - def __init__(self, size, target, genes=5): + def __init__(self, target, genes=100): """Initializes Evolution class. Args: - size (tuple): tuple containing height and width of target image (h, w). target (np.ndarray): target image for evolution. genes (int): the amount of circle to train the target image on. """ - self.size = size # Tuple (y, x) + self.size = target.shape self.target = target # Target Image self.generation = 1 self.genes = genes @@ -218,16 +216,16 @@

Args

# Randomization for Evolution y = random.randint(0, self.genes - 1) - change = random.randint(0, 6) + change = random.randint(0, new_specie.genotype_width + 1) - if change >= 6: + if change >= new_specie.genotype_width + 1: change -= 1 i, j = y, random.randint(0, self.genes - 1) i, j, s = (i, j, -1) if i < j else (j, i, 1) new_specie.genotype[i : j + 1] = np.roll(new_specie.genotype[i : j + 1], shift=s, axis=0) y = j - selection = np.random.choice(5, size=change, replace=False) + selection = np.random.choice(new_specie.genotype_width, size=change, replace=False) if random.random() < 0.25: new_specie.genotype[y, selection] = np.random.rand(len(selection)) @@ -346,16 +344,16 @@

Returns

# Randomization for Evolution y = random.randint(0, self.genes - 1) - change = random.randint(0, 6) + change = random.randint(0, new_specie.genotype_width + 1) - if change >= 6: + if change >= new_specie.genotype_width + 1: change -= 1 i, j = y, random.randint(0, self.genes - 1) i, j, s = (i, j, -1) if i < j else (j, i, 1) new_specie.genotype[i : j + 1] = np.roll(new_specie.genotype[i : j + 1], shift=s, axis=0) y = j - selection = np.random.choice(5, size=change, replace=False) + selection = np.random.choice(new_specie.genotype_width, size=change, replace=False) if random.random() < 0.25: new_specie.genotype[y, selection] = np.random.rand(len(selection)) @@ -421,9 +419,7 @@

-

Generated by pdoc 0.8.1.

+

Generated by pdoc 0.9.1.

- - \ No newline at end of file diff --git a/docs/fitness.html b/docs/fitness.html index 70900ad..10e9e72 100644 --- a/docs/fitness.html +++ b/docs/fitness.html @@ -3,15 +3,17 @@ - + circle_evolution.fitness API documentation - - - - + + + + + +
@@ -357,9 +359,7 @@

-

Generated by pdoc 0.8.1.

+

Generated by pdoc 0.9.1.

- - \ No newline at end of file diff --git a/docs/helpers.html b/docs/helpers.html index 08ef743..a398e52 100644 --- a/docs/helpers.html +++ b/docs/helpers.html @@ -3,15 +3,17 @@ - + circle_evolution.helpers API documentation - - - - + + + + + +
@@ -27,13 +29,9 @@

Module circle_evolution.helpers

"""Helper Functions"""
 import os
-
 import cv2
 
-import matplotlib.pyplot as plt
-
-
-def load_target_image(image_path, color=cv2.COLOR_BGR2GRAY, size=None):
+def load_target_image(image_path, color=True, size=None):
     """Loads images from image path.
 
     Loads and converts image to given colorspace for later processing using
@@ -41,7 +39,10 @@ 

Module circle_evolution.helpers

Args: image_path (str): path to load the image. - color: optional variable for colorspace conversion. + color (bool): if true the image is loaded as rgb, if false grayscale. + Defaults to true. + size (tuple): size of target image as (height, width). If None, then + original image dimension is kept. Returns: Image loaded from the path as a numpy.ndarray. @@ -51,25 +52,18 @@

Module circle_evolution.helpers

""" if not os.path.exists(image_path): raise FileNotFoundError(f"Image was not found at {image_path}") - img = cv2.imread(image_path) - # Performs Image Convertion - target = cv2.cvtColor(img, color) + + if color: + target = cv2.imread(image_path, cv2.IMREAD_COLOR) + # Switch from bgr to rgb + target = cv2.cvtColor(target, cv2.COLOR_BGR2RGB) + else: + target = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) + if size: # Only resizes image if it is needed! target = cv2.resize(src=target, dsize=size, interpolation=cv2.INTER_AREA) - return target - - -def show_image(img_arr): - """Displays image on window. - - Arguments: - img_arr (numpy.ndarray): image array to be displayed - """ - plt.figure() - plt.axis("off") - plt.imshow(img_arr, cmap="gray", vmin=0, vmax=255) - plt.show()
+ return target
@@ -80,7 +74,7 @@

Module circle_evolution.helpers

Functions

-def load_target_image(image_path, color=6, size=None) +def load_target_image(image_path, color=True, size=None)

Loads images from image path.

@@ -90,8 +84,12 @@

Args

image_path : str
path to load the image.
-
color
-
optional variable for colorspace conversion.
+
color : bool
+
if true the image is loaded as rgb, if false grayscale. +Defaults to true.
+
size : tuple
+
size of target image as (height, width). If None, then +original image dimension is kept.

Returns

Image loaded from the path as a numpy.ndarray.

@@ -104,7 +102,7 @@

Raises

Expand source code -
def load_target_image(image_path, color=cv2.COLOR_BGR2GRAY, size=None):
+
def load_target_image(image_path, color=True, size=None):
     """Loads images from image path.
 
     Loads and converts image to given colorspace for later processing using
@@ -112,7 +110,10 @@ 

Raises

Args: image_path (str): path to load the image. - color: optional variable for colorspace conversion. + color (bool): if true the image is loaded as rgb, if false grayscale. + Defaults to true. + size (tuple): size of target image as (height, width). If None, then + original image dimension is kept. Returns: Image loaded from the path as a numpy.ndarray. @@ -122,38 +123,20 @@

Raises

""" if not os.path.exists(image_path): raise FileNotFoundError(f"Image was not found at {image_path}") - img = cv2.imread(image_path) - # Performs Image Convertion - target = cv2.cvtColor(img, color) + + if color: + target = cv2.imread(image_path, cv2.IMREAD_COLOR) + # Switch from bgr to rgb + target = cv2.cvtColor(target, cv2.COLOR_BGR2RGB) + else: + target = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) + if size: # Only resizes image if it is needed! target = cv2.resize(src=target, dsize=size, interpolation=cv2.INTER_AREA) return target
-
-def show_image(img_arr) -
-
-

Displays image on window.

-

Arguments

-

img_arr (numpy.ndarray): image array to be displayed

-
- -Expand source code - -
def show_image(img_arr):
-    """Displays image on window.
-
-    Arguments:
-        img_arr (numpy.ndarray): image array to be displayed
-    """
-    plt.figure()
-    plt.axis("off")
-    plt.imshow(img_arr, cmap="gray", vmin=0, vmax=255)
-    plt.show()
-
-
@@ -173,16 +156,13 @@

Index

  • Functions

  • - - \ No newline at end of file diff --git a/docs/index.html b/docs/index.html index d50ed10..df291d1 100644 --- a/docs/index.html +++ b/docs/index.html @@ -3,15 +3,17 @@ - + circle_evolution API documentation - - - - + + + + + +
    @@ -73,19 +75,22 @@

    Python Example Scripts

    target = helpers.load_target_image("Mona Lisa 64.jpg", size=(64, 64)) # Setup evolution -e = evolution.Evolution((64, 64), target, genes=256) +e = evolution.Evolution((64, 64), target) # Evolve for 50k generations e.evolve(max_generation=50000) # Show evolved phenotype -helpers.show_image(e.specie.phenotype) +e.specie.show_img() # Saves genotype to checkpoint np.savetxt("Checkpoint.txt", e.specie.genotype) # Saves phenotype -cv2.imwrite("OuputImage.jpg", e.specie.phenotype) +e.specie.save_img("OutputImage.jpg") + +# Saves phenotype, resized +e.specie.save_img("OutputImage128x128.jpg", (128, 128))

    Here is how to load and train further from a saved checkpoint.

    from circle_evolution import evolution
    @@ -107,7 +112,7 @@ 

    Python Example Scripts

    e.evolve(max_generation=50000) # Show evolved phenotype -helpers.show_image(e.specie.phenotype) +e.specie.show_img()

    Contributing

    Pull requests are welcome. @@ -176,13 +181,16 @@

    Contributing

    e.evolve(max_generation=50000) # Show evolved phenotype -helpers.show_image(e.specie.phenotype) +e.specie.show_img() # Saves genotype to checkpoint np.savetxt("Checkpoint.txt", e.specie.genotype) # Saves phenotype -cv2.imwrite("OuputImage.jpg", e.specie.phenotype) +e.specie.save_img("OutputImage.jpg") + +# Saves phenotype, resized +e.specie.save_img("OutputImage128x128.jpg", (128, 128)) ``` Here is how to load and train further from a saved checkpoint. @@ -207,7 +215,7 @@

    Contributing

    e.evolve(max_generation=50000) # Show evolved phenotype -helpers.show_image(e.specie.phenotype) +e.specie.show_img() ``` # Contributing @@ -216,7 +224,7 @@

    Contributing

    For major changes, please open an issue first to discuss what you would like to change. """ -__version__ = "0.0.dev"
    +__version__ = "0.1"
    @@ -236,7 +244,7 @@

    Sub-modules

    circle_evolution.main
    -

    CLI interface for Circle Evolution

    +

    CLI for Circle Evolution

    circle_evolution.species
    @@ -283,9 +291,7 @@

    Index

    - - - + \ No newline at end of file diff --git a/docs/main.html b/docs/main.html index 797bd06..b15f72f 100644 --- a/docs/main.html +++ b/docs/main.html @@ -3,15 +3,17 @@ - + circle_evolution.main API documentation - - - - - + + + + + + +
    @@ -20,41 +22,43 @@

    Module circle_evolution.main

    -

    CLI interface for Circle Evolution

    +

    CLI for Circle Evolution

    Expand source code -
    """CLI interface for Circle Evolution"""
    +
    """CLI for Circle Evolution"""
     
     import argparse
     
     import numpy as np
     
    +from circle_evolution import __version__
     from circle_evolution.evolution import Evolution
     
     import circle_evolution.helpers as helpers
     
     
    +SIZE_OPTIONS = {1: (64, 64), 2: (128, 128), 3: (256, 256), 'auto': None}
    +
    +
     def main():
         """Entrypoint of application"""
    -    parser = argparse.ArgumentParser(description="Circle Evolution CLI")
    +    parser = argparse.ArgumentParser(description=f"Circle Evolution CLI v{__version__}")
     
         parser.add_argument("image", type=str, help="Image to be processed")
    -    size_options = {1: (64, 64), 2: (128, 128), 3: (256, 256)}
    -    parser.add_argument("--size", choices=size_options.keys(), default=2, help="Dimension of the image", type=int)
    +    parser.add_argument("--size", choices=SIZE_OPTIONS.keys(), default='auto', help="Dimension of the image")
         parser.add_argument("--genes", default=256, type=int, help="Number of genes")
         parser.add_argument("--max-generations", type=int, default=500000)
         args = parser.parse_args()
     
    -    target = helpers.load_target_image(args.image, size=size_options[args.size])
    +    target = helpers.load_target_image(args.image, size=SIZE_OPTIONS[args.size])
     
    -    evolution = Evolution(size_options[args.size], target, genes=args.genes)
    +    evolution = Evolution(target, genes=args.genes)
         evolution.evolve(max_generation=args.max_generations)
     
         evolution.specie.render()
    -
    -    helpers.show_image(evolution.specie.phenotype)
    +    evolution.specie.show_img()
     
         output_path_checkpoint = "checkpoint-{}.txt".format(evolution.generation)
         np.savetxt(output_path_checkpoint, evolution.specie.genotype)
    @@ -82,23 +86,21 @@ 

    Functions

    def main():
         """Entrypoint of application"""
    -    parser = argparse.ArgumentParser(description="Circle Evolution CLI")
    +    parser = argparse.ArgumentParser(description=f"Circle Evolution CLI v{__version__}")
     
         parser.add_argument("image", type=str, help="Image to be processed")
    -    size_options = {1: (64, 64), 2: (128, 128), 3: (256, 256)}
    -    parser.add_argument("--size", choices=size_options.keys(), default=2, help="Dimension of the image", type=int)
    +    parser.add_argument("--size", choices=SIZE_OPTIONS.keys(), default='auto', help="Dimension of the image")
         parser.add_argument("--genes", default=256, type=int, help="Number of genes")
         parser.add_argument("--max-generations", type=int, default=500000)
         args = parser.parse_args()
     
    -    target = helpers.load_target_image(args.image, size=size_options[args.size])
    +    target = helpers.load_target_image(args.image, size=SIZE_OPTIONS[args.size])
     
    -    evolution = Evolution(size_options[args.size], target, genes=args.genes)
    +    evolution = Evolution(target, genes=args.genes)
         evolution.evolve(max_generation=args.max_generations)
     
         evolution.specie.render()
    -
    -    helpers.show_image(evolution.specie.phenotype)
    +    evolution.specie.show_img()
     
         output_path_checkpoint = "checkpoint-{}.txt".format(evolution.generation)
         np.savetxt(output_path_checkpoint, evolution.specie.genotype)
    @@ -129,9 +131,7 @@

    Index

    - - \ No newline at end of file diff --git a/docs/species.html b/docs/species.html index 3abd984..a0c745a 100644 --- a/docs/species.html +++ b/docs/species.html @@ -3,15 +3,17 @@ - + circle_evolution.species API documentation - - - - + + + + + +
    @@ -34,7 +36,7 @@

    Module circle_evolution.species

    """ import cv2 - +from PIL import Image import numpy as np @@ -61,7 +63,8 @@

    Module circle_evolution.species

    genotype (np.ndarray): optional - initializes Specie with given genotype. """ self.size = size - self.genotype = genotype if genotype is not None else np.random.rand(genes, 5) + self.genotype_width = 5 if len(size) < 3 else 7 + self.genotype = genotype if genotype is not None else np.random.rand(genes, self.genotype_width) self.phenotype = np.zeros(size) @property @@ -76,20 +79,78 @@

    Module circle_evolution.species

    iteration given the genotype. After render() is done executing, the Specie phenotype it set to reflect latest changes in the genotype. """ - self.phenotype[:, :] = 0 + self.phenotype.fill(0) radius_avg = (self.size[0] + self.size[1]) / 2 / 6 for row in self.genotype: overlay = self.phenotype.copy() + color = (row[3:-1] * 255).astype(int).tolist() cv2.circle( overlay, center=(int(row[1] * self.size[1]), int(row[0] * self.size[0])), radius=int(row[2] * radius_avg), - color=(int(row[3] * 255)), + color=color, thickness=-1, ) - alpha = row[4] - self.phenotype = cv2.addWeighted(overlay, alpha, self.phenotype, 1 - alpha, 0)
    + alpha = row[-1] + self.phenotype = cv2.addWeighted(overlay, alpha, self.phenotype, 1 - alpha, 0) + + def save_checkpoint(self, fname, text=False): + """Save genotype to a checkpoint. + + Args: + fname: the file you would like to save to. + text (bool): whether to save as text or numpy format. Default: False + """ + if text: + np.savetxt(fname, self.genotype) + else: + np.save(fname, self.genotype) + + def load_checkpoint(self, fname, text=False): + """Load genotype from a checkpoint. + + Args: + fname: the file you would like to load from. + text (bool): whether to load as text or numpy format. Default: False + """ + if text: + self.genotype = np.loadtxt(fname) + else: + self.genotype = np.load(fname) + + def show_img(self, resolution=None): + """ + Displays image of phenotype. + + Args: + resolution (tuple): (height, width) of target image. + If None, uses target image resolution. Defaults to None. + """ + im = Image.fromarray(self.phenotype.astype("uint8")) + + if resolution is None: + im.show() + else: + im_resized = im.resize(resolution) + im_resized.show() + + def save_img(self, fname, resolution=None): + """ + Saves image of phenotype. + + Args: + fname (string): Filename to save the image to. Includes format postfix, e.g. `jpg` or `png`. + resolution (tuple): (height, width) of target image. + If None, uses target image resolution. Defaults to None. + """ + im = Image.fromarray(self.phenotype.astype("uint8")) + + if resolution is None: + im.save(fname) + else: + im_resized = im.resize(resolution) + im_resized.save(fname)
    @@ -158,7 +219,8 @@

    Args

    genotype (np.ndarray): optional - initializes Specie with given genotype. """ self.size = size - self.genotype = genotype if genotype is not None else np.random.rand(genes, 5) + self.genotype_width = 5 if len(size) < 3 else 7 + self.genotype = genotype if genotype is not None else np.random.rand(genes, self.genotype_width) self.phenotype = np.zeros(size) @property @@ -173,20 +235,78 @@

    Args

    iteration given the genotype. After render() is done executing, the Specie phenotype it set to reflect latest changes in the genotype. """ - self.phenotype[:, :] = 0 + self.phenotype.fill(0) radius_avg = (self.size[0] + self.size[1]) / 2 / 6 for row in self.genotype: overlay = self.phenotype.copy() + color = (row[3:-1] * 255).astype(int).tolist() cv2.circle( overlay, center=(int(row[1] * self.size[1]), int(row[0] * self.size[0])), radius=int(row[2] * radius_avg), - color=(int(row[3] * 255)), + color=color, thickness=-1, ) - alpha = row[4] - self.phenotype = cv2.addWeighted(overlay, alpha, self.phenotype, 1 - alpha, 0) + alpha = row[-1] + self.phenotype = cv2.addWeighted(overlay, alpha, self.phenotype, 1 - alpha, 0) + + def save_checkpoint(self, fname, text=False): + """Save genotype to a checkpoint. + + Args: + fname: the file you would like to save to. + text (bool): whether to save as text or numpy format. Default: False + """ + if text: + np.savetxt(fname, self.genotype) + else: + np.save(fname, self.genotype) + + def load_checkpoint(self, fname, text=False): + """Load genotype from a checkpoint. + + Args: + fname: the file you would like to load from. + text (bool): whether to load as text or numpy format. Default: False + """ + if text: + self.genotype = np.loadtxt(fname) + else: + self.genotype = np.load(fname) + + def show_img(self, resolution=None): + """ + Displays image of phenotype. + + Args: + resolution (tuple): (height, width) of target image. + If None, uses target image resolution. Defaults to None. + """ + im = Image.fromarray(self.phenotype.astype("uint8")) + + if resolution is None: + im.show() + else: + im_resized = im.resize(resolution) + im_resized.show() + + def save_img(self, fname, resolution=None): + """ + Saves image of phenotype. + + Args: + fname (string): Filename to save the image to. Includes format postfix, e.g. `jpg` or `png`. + resolution (tuple): (height, width) of target image. + If None, uses target image resolution. Defaults to None. + """ + im = Image.fromarray(self.phenotype.astype("uint8")) + + if resolution is None: + im.save(fname) + else: + im_resized = im.resize(resolution) + im_resized.save(fname)

    Instance variables

    @@ -206,6 +326,35 @@

    Instance variables

    Methods

    +
    +def load_checkpoint(self, fname, text=False) +
    +
    +

    Load genotype from a checkpoint.

    +

    Args

    +
    +
    fname
    +
    the file you would like to load from.
    +
    text : bool
    +
    whether to load as text or numpy format. Default: False
    +
    +
    + +Expand source code + +
    def load_checkpoint(self, fname, text=False):
    +    """Load genotype from a checkpoint.
    +
    +    Args:
    +        fname: the file you would like to load from.
    +        text (bool): whether to load as text or numpy format. Default: False
    +    """
    +    if text:
    +        self.genotype = np.loadtxt(fname)
    +    else:
    +        self.genotype = np.load(fname)
    +
    +
    def render(self)
    @@ -225,22 +374,119 @@

    Methods

    iteration given the genotype. After render() is done executing, the Specie phenotype it set to reflect latest changes in the genotype. """ - self.phenotype[:, :] = 0 + self.phenotype.fill(0) radius_avg = (self.size[0] + self.size[1]) / 2 / 6 for row in self.genotype: overlay = self.phenotype.copy() + color = (row[3:-1] * 255).astype(int).tolist() cv2.circle( overlay, center=(int(row[1] * self.size[1]), int(row[0] * self.size[0])), radius=int(row[2] * radius_avg), - color=(int(row[3] * 255)), + color=color, thickness=-1, ) - alpha = row[4] + alpha = row[-1] self.phenotype = cv2.addWeighted(overlay, alpha, self.phenotype, 1 - alpha, 0) +
    +def save_checkpoint(self, fname, text=False) +
    +
    +

    Save genotype to a checkpoint.

    +

    Args

    +
    +
    fname
    +
    the file you would like to save to.
    +
    text : bool
    +
    whether to save as text or numpy format. Default: False
    +
    +
    + +Expand source code + +
    def save_checkpoint(self, fname, text=False):
    +    """Save genotype to a checkpoint.
    +
    +    Args:
    +        fname: the file you would like to save to.
    +        text (bool): whether to save as text or numpy format. Default: False
    +    """
    +    if text:
    +        np.savetxt(fname, self.genotype)
    +    else:
    +        np.save(fname, self.genotype)
    +
    +
    +
    +def save_img(self, fname, resolution=None) +
    +
    +

    Saves image of phenotype.

    +

    Args

    +
    +
    fname : string
    +
    Filename to save the image to. Includes format postfix, e.g. jpg or png.
    +
    resolution : tuple
    +
    (height, width) of target image. +If None, uses target image resolution. Defaults to None.
    +
    +
    + +Expand source code + +
    def save_img(self, fname, resolution=None):
    +    """
    +    Saves image of phenotype.
    +
    +    Args:
    +        fname (string): Filename to save the image to. Includes format postfix, e.g. `jpg` or `png`.
    +        resolution (tuple): (height, width) of target image.
    +            If None, uses target image resolution. Defaults to None.
    +    """
    +    im = Image.fromarray(self.phenotype.astype("uint8"))
    +
    +    if resolution is None:
    +        im.save(fname)
    +    else:
    +        im_resized = im.resize(resolution)
    +        im_resized.save(fname)
    +
    +
    +
    +def show_img(self, resolution=None) +
    +
    +

    Displays image of phenotype.

    +

    Args

    +
    +
    resolution : tuple
    +
    (height, width) of target image. +If None, uses target image resolution. Defaults to None.
    +
    +
    + +Expand source code + +
    def show_img(self, resolution=None):
    +    """
    +    Displays image of phenotype.
    +
    +    Args:
    +        resolution (tuple): (height, width) of target image.
    +            If None, uses target image resolution. Defaults to None.
    +    """
    +    im = Image.fromarray(self.phenotype.astype("uint8"))
    +
    +    if resolution is None:
    +        im.show()
    +    else:
    +        im_resized = im.resize(resolution)
    +        im_resized.show()
    +
    +
    @@ -261,9 +507,13 @@

    Index