{"id":20703204,"url":"https://github.com/ahmedfgad/gari","last_synced_at":"2026-03-05T19:34:22.068Z","repository":{"id":49282623,"uuid":"123811235","full_name":"ahmedfgad/GARI","owner":"ahmedfgad","description":"GARI (Genetic Algorithm for Reproducing Images) reproduces a single image using Genetic Algorithm (GA) by evolving pixel values.","archived":false,"fork":false,"pushed_at":"2023-04-08T19:41:48.000Z","size":49,"stargazers_count":59,"open_issues_count":1,"forks_count":32,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-23T00:17:43.241Z","etag":null,"topics":["evolutionary-algorithms","genetic-algorithm","genetic-analysis","image-analysis","image-manipulation","image-processing","image-reproduction","optimization-algorithms","python","python3"],"latest_commit_sha":null,"homepage":"https://www.linkedin.com/in/ahmedfgad/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ahmedfgad.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null},"funding":{"github":null,"open_collective":"pygad","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":["https://donate.stripe.com/eVa5kO866elKgM0144","http://paypal.me/ahmedfgad"]}},"created_at":"2018-03-04T17:20:32.000Z","updated_at":"2025-03-06T08:36:55.000Z","dependencies_parsed_at":"2023-12-14T08:46:42.942Z","dependency_job_id":null,"html_url":"https://github.com/ahmedfgad/GARI","commit_stats":{"total_commits":25,"total_committers":1,"mean_commits":25.0,"dds":0.0,"last_synced_commit":"0d930d7c41b6ee845b33108112f151c850b5e1c5"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmedfgad%2FGARI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmedfgad%2FGARI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmedfgad%2FGARI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmedfgad%2FGARI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ahmedfgad","download_url":"https://codeload.github.com/ahmedfgad/GARI/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250343960,"owners_count":21415042,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["evolutionary-algorithms","genetic-algorithm","genetic-analysis","image-analysis","image-manipulation","image-processing","image-reproduction","optimization-algorithms","python","python3"],"created_at":"2024-11-17T01:06:45.249Z","updated_at":"2026-03-05T19:34:20.721Z","avatar_url":"https://github.com/ahmedfgad.png","language":"Python","funding_links":["https://opencollective.com/pygad","https://donate.stripe.com/eVa5kO866elKgM0144","http://paypal.me/ahmedfgad"],"categories":[],"sub_categories":[],"readme":"# GARI\nGARI (Genetic Algorithm for Reproducing Images) is a Python project that uses the PyGAD library for reproducing images using the genetic algorithm. GARI reproduces a single image using Genetic Algorithm (GA) by evolving pixel values. This project works with both color and gray images.\n\nFor implementing the genetic algorithm, the PyGAD library is used. Check its documentation here: https://pygad.readthedocs.io\n\n**IMPORTANT** *If you are coming for the code of the tutorial [Reproducing Images using a Genetic Algorithm with Python](https://heartbeat.fritz.ai/reproducing-images-using-a-genetic-algorithm-with-python-91fc701ff84), then it has been moved to the [TutorialProject](https://github.com/ahmedfgad/GARI/tree/master/TutorialProject) directory on 18 May 2020.*\n\n# PyGAD Installation\n\nTo install [PyGAD](https://pypi.org/project/pygad), simply use pip to download and install the library from [PyPI](https://pypi.org/project/pygad) (Python Package Index). The library lives a PyPI at this page https://pypi.org/project/pygad.\n\nFor Windows, issue the following command:\n\n```python\npip install pygad\n```\n\nFor Linux and Mac, replace `pip` by use `pip3` because the library only supports Python 3.\n\n```python\npip3 install pygad\n```\n\nPyGAD is developed in Python 3.7.3 and depends on NumPy for creating and manipulating arrays and Matplotlib for creating figures. The exact NumPy version used in developing PyGAD is 1.16.4. For Matplotlib, the version is 3.1.0.\n\n# Project Steps\n\nThe steps to follow in order to reproduce an image are as follows:\n\n- Read an image\n- Prepare the fitness function\n- Create an instance of the pygad.GA class with the appropriate parameters\n- Run PyGAD\n- Plot results\n- Calculate some statistics\n\nThe next sections discusses the code of each of these steps.\n\n## Read an Image\n\nThere is an image named `fruit.jpg` in the project which is read according to the next code.\n\n```python\nimport imageio\nimport numpy\n\ntarget_im = imageio.imread('fruit.jpg')\ntarget_im = numpy.asarray(target_im/255, dtype=numpy.float)\n```\n\nHere is the read image.\n\n![fruit](https://user-images.githubusercontent.com/16560492/36948808-f0ac882e-1fe8-11e8-8d07-1307e3477fd0.jpg)\n\nBased on the chromosome representation used in the example, the pixel values can be either in the 0-255, 0-1, or any other ranges. \n\nNote that the range of pixel values affect other parameters like the range from which the random values are selected during mutation and also the range of the values used in the initial population. So, be consistent.\n\n## Prepare the Fitness Function\n\nThe next code creates a function that will be used as a fitness function for calculating the fitness value for each solution in the population. This function must be a maximization function that accepts 2 parameters representing a solution and its index. It returns a value representing the fitness value.\n\nThe fitness value is calculated using the sum of absolute difference between genes values in the original and reproduced chromosomes. The `gari.img2chromosome()` function is called before the fitness function to represent the image as a vector because the genetic algorithm can work with 1D chromosomes. \n\nFor more information about preparing the fitness function in PyGAD, please read the [PyGAD's documentation](https://pygad.readthedocs.io).\n\n```python\ntarget_chromosome = gari.img2chromosome(target_im)\n\ndef fitness_fun(solution, solution_idx):\n    fitness = numpy.sum(numpy.abs(target_chromosome-solution))\n\n    # Negating the fitness value to make it increasing rather than decreasing.\n    fitness = numpy.sum(target_chromosome) - fitness\n    return fitness\n```\n\n## Create an Instance of the `pygad.GA` Class\n\nIt is very important to use random mutation and set the `mutation_by_replacement` to `True`. Based on the range of pixel values, the values assigned to the `init_range_low`, `init_range_high`, `random_mutation_min_val`, and `random_mutation_max_val` parameters should be changed.\n\nIf the image pixel values range from 0 to 255, then set `init_range_low` and `random_mutation_min_val` to 0 as they are but change `init_range_high` and `random_mutation_max_val` to 255.\n\nFeel free to change the other parameters or add other parameters. Please check the [PyGAD's documentation](https://pygad.readthedocs.io) for the full list of parameters. \n\n```python\nimport pygad\n\nga_instance = pygad.GA(num_generations=20000,\n                       num_parents_mating=10,\n                       fitness_func=fitness_fun,\n                       sol_per_pop=20,\n                       num_genes=target_im.size,\n                       init_range_low=0.0,\n                       init_range_high=1.0,\n                       mutation_percent_genes=0.01,\n                       mutation_type=\"random\",\n                       mutation_by_replacement=True,\n                       random_mutation_min_val=0.0,\n                       random_mutation_max_val=1.0)\n```\n\n## Run PyGAD\n\nSimply, call the `run()` method to run PyGAD.\n\n```python\nga_instance.run()\n```\n\n## Plot Results\n\nAfter the `run()` method completes, the fitness values of all generations can be viewed in a plot using the `plot_result()` method.\n\n```python\nga_instance.plot_result()\n```\n\nHere is the plot after 20,000 generations.\n\n![Fitness Values](https://user-images.githubusercontent.com/16560492/82232124-77762c00-992e-11ea-9fc6-14a1cd7a04ff.png)\n\n## Calculate Some Statistics\n\nHere is some information about the best solution. \n\n```python\n# Returning the details of the best solution.\nsolution, solution_fitness, solution_idx = ga_instance.best_solution()\nprint(\"Fitness value of the best solution = {solution_fitness}\".format(solution_fitness=solution_fitness))\nprint(\"Index of the best solution : {solution_idx}\".format(solution_idx=solution_idx))\n\nif ga_instance.best_solution_generation != -1:\n    print(\"Best fitness value reached after {best_solution_generation} generations.\".format(best_solution_generation=ga_instance.best_solution_generation))\n\nresult = gari.chromosome2img(solution, target_im.shape)\nmatplotlib.pyplot.imshow(result)\nmatplotlib.pyplot.title(\"PyGAD \u0026 GARI for Reproducing Images\")\nmatplotlib.pyplot.show()\n```\n\n# Evolution by Generation\n\nThe solution reached after the 20,000 generations is shown below.\n\n![solution](https://user-images.githubusercontent.com/16560492/82232405-e0f63a80-992e-11ea-984f-b6ed76465bd1.png)\n\nAfter more generations, the result can be enhanced like what shown below.\n\n![solution](https://user-images.githubusercontent.com/16560492/82232345-cf149780-992e-11ea-8390-bf1a57a19de7.png)\n\nThe results can also be enhanced by changing the parameters passed to the constructor of the `pygad.GA` class.\n\nHere is an example of input image and how it is evolved after some iterations.\n\n\u003ch1\u003eGeneration 0\u003c/h1\u003e\n\n![solution_0](https://user-images.githubusercontent.com/16560492/36948589-b47276f0-1fe5-11e8-8efe-0cd1a225ea3a.png)\n\n\u003ch1\u003eGeneration 1,000\u003c/h1\u003e\n\n![solution_1000](https://user-images.githubusercontent.com/16560492/36948823-16f490ee-1fe9-11e8-97db-3e8905ad5440.png)\n\n\u003ch1\u003eGeneration 2,500\u003c/h1\u003e\n\n![solution_2500](https://user-images.githubusercontent.com/16560492/36948832-3f314b60-1fe9-11e8-8f4a-4d9a53b99f3d.png)\n\n\u003ch1\u003eGeneration 4,500\u003c/h1\u003e\n\n![solution_4500](https://user-images.githubusercontent.com/16560492/36948837-53d1849a-1fe9-11e8-9b36-e9e9291e347b.png)\n\n\u003ch1\u003eGeneration 7,000\u003c/h1\u003e\n\n![solution_7000](https://user-images.githubusercontent.com/16560492/36948852-66f1b176-1fe9-11e8-9f9b-460804e94004.png)\n\n\u003ch1\u003eGeneration 8,500\u003c/h1\u003e\n\n![solution_8500](https://user-images.githubusercontent.com/16560492/36948865-7fbb5158-1fe9-11e8-8c04-8ac3c1f7b1b1.png)\n\n\u003ch1\u003eGeneration 20,000\u003c/h1\u003e\n\n![solution](https://user-images.githubusercontent.com/16560492/82232405-e0f63a80-992e-11ea-984f-b6ed76465bd1.png)\n\n# For More Information\n\nThere are different resources that can be used to get started with the building CNN and its Python implementation. \n\n## Tutorial: Reproduce Images with Genetic Algorithm\n\nIn 1 May 2019, I wrote a tutorial discussing this project. The tutorial is titled [**Reproducing Images using a Genetic Algorithm with Python**](https://www.linkedin.com/pulse/reproducing-images-using-genetic-algorithm-python-ahmed-gad) which is published at Heartbeat. Check it at these links:\n\n- [Heartbeat](https://heartbeat.fritz.ai/reproducing-images-using-a-genetic-algorithm-with-python-91fc701ff84): https://heartbeat.fritz.ai/reproducing-images-using-a-genetic-algorithm-with-python-91fc701ff84\n- [LinkedIn](https://www.linkedin.com/pulse/reproducing-images-using-genetic-algorithm-python-ahmed-gad): https://www.linkedin.com/pulse/reproducing-images-using-genetic-algorithm-python-ahmed-gad\n\n[![Tutorial Cover Image](https://miro.medium.com/max/2560/1*47K2h_Zz6SQVMHW2NL-WsQ.jpeg)](https://heartbeat.fritz.ai/reproducing-images-using-a-genetic-algorithm-with-python-91fc701ff84)\n\n## Book: Practical Computer Vision Applications Using Deep Learning with CNNs\n\nYou can also check my book cited as [**Ahmed Fawzy Gad 'Practical Computer Vision Applications Using Deep Learning with CNNs'. Dec. 2018, Apress, 978-1-4842-4167-7**](https://www.amazon.com/Practical-Computer-Vision-Applications-Learning/dp/1484241665) which discusses neural networks, convolutional neural networks, deep learning, genetic algorithm, and more.\n\nFind the book at these links:\n\n- [Amazon](https://www.amazon.com/Practical-Computer-Vision-Applications-Learning/dp/1484241665)\n- [Springer](https://link.springer.com/book/10.1007/978-1-4842-4167-7)\n- [Apress](https://www.apress.com/gp/book/9781484241660)\n- [O'Reilly](https://www.oreilly.com/library/view/practical-computer-vision/9781484241677)\n- [Google Books](https://books.google.com.eg/books?id=xLd9DwAAQBAJ)\n\n![Fig04](https://user-images.githubusercontent.com/16560492/78830077-ae7c2800-79e7-11ea-980b-53b6bd879eeb.jpg)\n\n# Citing PyGAD - Bibtex Formatted Citation\n\nIf you used PyGAD, please consider adding a citation to the following paper about PyGAD:\n\n```\n@misc{gad2021pygad,\n      title={PyGAD: An Intuitive Genetic Algorithm Python Library}, \n      author={Ahmed Fawzy Gad},\n      year={2021},\n      eprint={2106.06158},\n      archivePrefix={arXiv},\n      primaryClass={cs.NE}\n}\n```\n\n# Contact Us\n\n* E-mail: ahmed.f.gad@gmail.com\n* [LinkedIn](https://www.linkedin.com/in/ahmedfgad)\n* [Amazon Author Page](https://amazon.com/author/ahmedgad)\n* [Heartbeat](https://heartbeat.fritz.ai/@ahmedfgad)\n* [Paperspace](https://blog.paperspace.com/author/ahmed)\n* [KDnuggets](https://kdnuggets.com/author/ahmed-gad)\n* [TowardsDataScience](https://towardsdatascience.com/@ahmedfgad)\n* [GitHub](https://github.com/ahmedfgad)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahmedfgad%2Fgari","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fahmedfgad%2Fgari","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahmedfgad%2Fgari/lists"}