File size: 2,251 Bytes
a4056fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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()