Spaces:
Sleeping
Sleeping
| from PIL import Image, ImageDraw | |
| import gradio as gr | |
| def halftone_effect(image, shape_type, grid_spacing=10, max_size=8): | |
| """ | |
| Apply a halftone effect to the input image using the specified shape type. | |
| Args: | |
| image (PIL.Image): Input image. | |
| shape_type (str): Type of shape ('circle', 'square', 'triangle'). | |
| grid_spacing (int): Distance between grid points in pixels (default: 10). | |
| max_size (int): Maximum size of shapes in pixels (default: 8). | |
| Returns: | |
| PIL.Image: Processed image with halftone effect. | |
| """ | |
| # Convert image to grayscale | |
| gray_image = image.convert('L') | |
| # Create a new image with white background | |
| output = Image.new('RGB', image.size, (255, 255, 255)) | |
| draw = ImageDraw.Draw(output) | |
| # Iterate over grid points | |
| for x in range(0, image.width, grid_spacing): | |
| for y in range(0, image.height, grid_spacing): | |
| # Get grayscale value (0 = black, 255 = white) | |
| g = gray_image.getpixel((x, y)) | |
| # Calculate shape size (larger for darker areas) | |
| size = max_size * (1 - g / 255) | |
| if size < 1: | |
| continue # Skip if size is too small | |
| # Draw the specified shape | |
| if shape_type == 'circle': | |
| bbox = [x - size/2, y - size/2, x + size/2, y + size/2] | |
| draw.ellipse(bbox, fill='black') | |
| elif shape_type == 'square': | |
| bbox = [x - size/2, y - size/2, x + size/2, y + size/2] | |
| draw.rectangle(bbox, fill='black') | |
| elif shape_type == 'triangle': | |
| p1 = (x, y - size/2) | |
| p2 = (x - size/2, y + size/2) | |
| p3 = (x + size/2, y + size/2) | |
| draw.polygon([p1, p2, p3], fill='black') | |
| return output | |
| # Define Gradio interface | |
| iface = gr.Interface( | |
| fn=halftone_effect, | |
| inputs=[ | |
| gr.Image(type="pil", label="Upload Image"), | |
| gr.Dropdown(["circle", "square", "triangle"], label="Shape Type") | |
| ], | |
| outputs=gr.Image(type="pil", label="Halftone Effect Output"), | |
| title="Halftone Effect App", | |
| description="Upload an image and select a shape to apply a halftone effect." | |
| ) | |
| # Launch the interface | |
| iface.launch() |