yusufgundogdu commited on
Commit
87c889e
·
verified ·
1 Parent(s): 322ebc5

Create halftone_method.py

Browse files
Files changed (1) hide show
  1. halftone_method.py +66 -0
halftone_method.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw
2
+ import io
3
+ import logging
4
+ from datetime import datetime
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ def halftone_effect(img, dot_size=10):
9
+ """
10
+ Apply a halftone effect to the input image.
11
+ """
12
+ grayscale = img.convert('L')
13
+ width, height = grayscale.size
14
+
15
+ halftone_image = Image.new('L', (width, height), color=255)
16
+ draw = ImageDraw.Draw(halftone_image)
17
+
18
+ for x in range(0, width, dot_size):
19
+ for y in range(0, height, dot_size):
20
+ block_width = min(dot_size, width - x)
21
+ block_height = min(dot_size, height - y)
22
+
23
+ region = grayscale.crop((x, y, x + block_width, y + block_height))
24
+ avg_brightness = sum(region.getdata()) / (block_width * block_height)
25
+
26
+ max_radius = dot_size // 2
27
+ radius = int((255 - avg_brightness) / 255 * max_radius)
28
+ radius = max(0, min(radius, max_radius))
29
+
30
+ center_x = x + dot_size // 2
31
+ center_y = y + dot_size // 2
32
+ draw.ellipse(
33
+ (
34
+ center_x - radius,
35
+ center_y - radius,
36
+ center_x + radius,
37
+ center_y + radius
38
+ ),
39
+ fill=0
40
+ )
41
+
42
+ return halftone_image
43
+
44
+ def apply_halftone(image_data, dot_size=10):
45
+ start_time = datetime.now()
46
+ logger.info(f"Applying halftone effect - {start_time}")
47
+
48
+ try:
49
+ input_image = Image.open(io.BytesIO(image_data))
50
+ logger.info(f"Image opened. Mode: {input_image.mode}, Size: {input_image.size}")
51
+
52
+ dot_size = max(5, min(20, dot_size))
53
+ logger.info(f"Applying halftone effect with dot size: {dot_size}")
54
+
55
+ output_image = halftone_effect(input_image, dot_size)
56
+
57
+ img_io = io.BytesIO()
58
+ output_image.save(img_io, 'PNG')
59
+ img_io.seek(0)
60
+
61
+ duration = (datetime.now() - start_time).total_seconds()
62
+ logger.info(f"Successfully processed. Duration: {duration} seconds")
63
+ return img_io
64
+ except Exception as e:
65
+ logger.error(f"Halftone processing error: {str(e)}", exc_info=True)
66
+ raise