akhaliq HF Staff commited on
Commit
f71fab4
·
verified ·
1 Parent(s): 4075eb5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw
3
+
4
+ def halftone_effect(img, dot_size=10):
5
+ """
6
+ Apply a halftone effect to the input image.
7
+
8
+ Parameters:
9
+ - img: PIL.Image object (input image)
10
+ - dot_size: int, spacing and maximum cell size for dot placement
11
+
12
+ Returns:
13
+ - PIL.Image object with halftone effect
14
+ """
15
+ # Convert to grayscale
16
+ grayscale = img.convert('L')
17
+ width, height = grayscale.size
18
+
19
+ # Create a new white image for the halftone effect
20
+ halftone_image = Image.new('L', (width, height), color=255)
21
+ draw = ImageDraw.Draw(halftone_image)
22
+
23
+ # Loop through the image in steps of dot_size
24
+ for x in range(0, width, dot_size):
25
+ for y in range(0, height, dot_size):
26
+ # Determine the size of the current block (to handle image edges)
27
+ block_width = min(dot_size, width - x)
28
+ block_height = min(dot_size, height - y)
29
+
30
+ # Extract the region of interest and calculate its average brightness
31
+ region = grayscale.crop((x, y, x + block_width, y + block_height))
32
+ avg_brightness = sum(region.getdata()) / (block_width * block_height)
33
+
34
+ # Calculate radius based on brightness (brighter = smaller dot)
35
+ max_radius = dot_size // 2
36
+ radius = int((255 - avg_brightness) / 255 * max_radius)
37
+ radius = max(0, min(radius, max_radius)) # Clamp radius between 0 and max_radius
38
+
39
+ # Draw the circle at the center of the current cell
40
+ center_x = x + dot_size // 2
41
+ center_y = y + dot_size // 2
42
+ draw.ellipse(
43
+ (
44
+ center_x - radius,
45
+ center_y - radius,
46
+ center_x + radius,
47
+ center_y + radius
48
+ ),
49
+ fill=0 # Black dot
50
+ )
51
+
52
+ return halftone_image
53
+
54
+ # Gradio Interface
55
+ interface = gr.Interface(
56
+ fn=halftone_effect,
57
+ inputs=[
58
+ gr.Image(type="pil", label="Upload an Image"),
59
+ gr.Slider(minimum=5, maximum=20, step=1, value=10, label="Dot Size")
60
+ ],
61
+ outputs=gr.Image(label="Halftone Image"),
62
+ title="Halftone Image Generator",
63
+ description="Convert any image into a stylized halftone effect using black dots.",
64
+ allow_flagging="never"
65
+ )
66
+
67
+ if __name__ == "__main__":
68
+ interface.launch()