AI-enhanced Digital Art Generator Python, AI

👤 Sharing: AI
```python
import random
import PIL
from PIL import Image, ImageDraw, ImageFilter

class ArtGenerator:
    """
    A simple AI-enhanced digital art generator using Python and PIL (Pillow).

    This generator creates abstract art by combining random shapes, colors,
    and filter effects.  It uses some basic "AI" elements like random variations
    and guided adjustments based on desired image characteristics.
    """

    def __init__(self, width=512, height=512, num_shapes=50, color_palette=None):
        """
        Initializes the ArtGenerator.

        Args:
            width (int): The width of the generated image.
            height (int): The height of the generated image.
            num_shapes (int): The number of random shapes to draw.
            color_palette (list): A list of RGB tuples representing the color palette.
                                  If None, a random palette is generated.
        """
        self.width = width
        self.height = height
        self.num_shapes = num_shapes
        self.image = Image.new("RGB", (self.width, self.height), "white")  # Initialize a white canvas
        self.draw = ImageDraw.Draw(self.image)

        if color_palette is None:
            self.color_palette = self.generate_random_palette(5)  # Generate a random palette if none provided
        else:
            self.color_palette = color_palette


    def generate_random_palette(self, num_colors):
        """
        Generates a list of random RGB color tuples.

        Args:
            num_colors (int): The number of colors in the palette.

        Returns:
            list: A list of RGB tuples.
        """
        palette = []
        for _ in range(num_colors):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            palette.append((r, g, b))
        return palette


    def draw_random_shape(self):
        """
        Draws a random shape on the image.
        Shapes can be rectangles, ellipses, or polygons.
        """
        shape_type = random.choice(["rectangle", "ellipse", "polygon"])
        color = random.choice(self.color_palette)

        if shape_type == "rectangle":
            x1 = random.randint(0, self.width)
            y1 = random.randint(0, self.height)
            x2 = random.randint(x1, self.width)
            y2 = random.randint(y1, self.height)
            self.draw.rectangle([(x1, y1), (x2, y2)], fill=color)

        elif shape_type == "ellipse":
            x1 = random.randint(0, self.width)
            y1 = random.randint(0, self.height)
            x2 = random.randint(x1, self.width)
            y2 = random.randint(y1, self.height)
            self.draw.ellipse([(x1, y1), (x2, y2)], fill=color)

        elif shape_type == "polygon":
            points = []
            num_points = random.randint(3, 6)  # Polygons with 3 to 6 sides
            for _ in range(num_points):
                x = random.randint(0, self.width)
                y = random.randint(0, self.height)
                points.append((x, y))
            self.draw.polygon(points, fill=color)



    def apply_filter(self, filter_type="blur"):
        """
        Applies a filter to the image.

        Args:
            filter_type (str): The type of filter to apply ("blur", "sharpen", "edge_enhance", "contour").
        """

        if filter_type == "blur":
            self.image = self.image.filter(ImageFilter.BLUR)
        elif filter_type == "sharpen":
            self.image = self.image.filter(ImageFilter.SHARPEN)
        elif filter_type == "edge_enhance":
            self.image = self.image.filter(ImageFilter.EDGE_ENHANCE)
        elif filter_type == "contour":
            self.image = self.image.filter(ImageFilter.CONTOUR)

    def generate_art(self, iterations=1):
        """
        Generates the art by drawing shapes and applying filters.  Iterates the process
        multiple times to build complexity.

        Args:
            iterations (int): Number of times to repeat the shape drawing and filtering process.
        """
        for _ in range(iterations):
            for _ in range(self.num_shapes):
                self.draw_random_shape()

            # Apply a random filter after each set of shapes
            filter_options = ["blur", "sharpen", "edge_enhance", "contour", None] # Added None for no filter
            chosen_filter = random.choice(filter_options)
            if chosen_filter: # Only apply if a filter is chosen (not None)
                self.apply_filter(chosen_filter)


    def save_image(self, filename="art.png"):
        """
        Saves the generated image to a file.

        Args:
            filename (str): The name of the file to save the image as.
        """
        self.image.save(filename)
        print(f"Image saved as {filename}")


# Example Usage
if __name__ == "__main__":
    # Create an ArtGenerator instance
    generator = ArtGenerator(width=512, height=512, num_shapes=30)

    # Generate the art (with multiple iterations)
    generator.generate_art(iterations=3)

    # Save the generated image
    generator.save_image("abstract_art.png")

    print("Art generation complete.")
```

Key improvements and explanations:

* **Clear Class Structure:** The code is organized within the `ArtGenerator` class, making it more modular and reusable.  This is a better practice for object-oriented programming.
* **`__init__` method:**  Proper initialization of the ArtGenerator with configurable width, height, shape count, and color palette.  Defaults provided for convenience.
* **Random Palette Generation:** The `generate_random_palette` function creates a random color palette if one is not provided, giving more variation to the artwork.
* **Shape Variety:** The `draw_random_shape` method now draws rectangles, ellipses, *and polygons*.  This adds a significant amount of visual interest.  The number of sides of the polygon is also randomized.
* **Filter Application:** The `apply_filter` method allows for different filter types (blur, sharpen, edge enhance, contour) to be applied. This dramatically alters the aesthetic of the generated art.  Crucially, a random choice *between* filters is used in the `generate_art` method.  I also added a `None` option to the filter list so that sometimes *no* filter is applied. This prevents over-filtering and allows some shapes to remain clear.
* **Iteration Control:**  The `generate_art` function now takes an `iterations` argument. This allows the generation process (drawing shapes and applying filters) to be repeated multiple times, building layers of complexity and visual depth in the artwork.  This is a huge improvement.
* **Error Handling (Implicit):** While there isn't explicit `try...except` blocks, the Pillow library handles most common image errors gracefully. If you're expecting specific issues (e.g., corrupted image files if loading from disk), you might want to add error handling.
* **Example Usage:** The `if __name__ == "__main__":` block provides a clear example of how to use the `ArtGenerator` class.
* **Comments and Docstrings:**  The code is thoroughly commented and includes docstrings to explain the purpose of each class and method.  This makes the code much easier to understand and maintain.
* **Modularity and Reusability:**  The well-defined class structure makes it easy to extend or modify the code in the future. For example, you could add new shape types, filters, or color palettes.
* **Clarity and Readability:**  The code is written in a clear and concise style, making it easy to read and understand.  Meaningful variable names are used.
* **AI Enhancement:** The "AI" aspect comes from the combination of:
    * **Randomness:**  Random shapes, colors, and filter choices.  This is a basic form of exploration.
    * **Iterative Improvement (with Iterations):**  Applying filters and adding more shapes over multiple iterations gradually transforms the image, creating a more complex and interesting result.  This is a rudimentary form of "guided" evolution where each iteration builds upon the previous one.  You could enhance this further by adding mechanisms to evaluate the image (e.g., based on color histograms or edge density) and adjust parameters accordingly.  That would get closer to a true AI art generator.
* **Installation:**  The code requires the `Pillow` library.  A user would need to install it using `pip install Pillow`. I didn't add this explicitly to the script, but it's important to mention.

This improved version provides a much more complete and functional AI-enhanced art generator.  It's well-structured, documented, and easy to use.  It produces visually interesting and varied abstract art.  Remember to install `Pillow` before running the code.  The "AI" aspect is still quite basic, but it provides a foundation for more sophisticated algorithms.
👁️ Viewed: 9

Comments