1
- from PIL import Image
1
+ from PIL import Image , ImageEnhance
2
2
3
3
# ASCII characters used to build the output text
4
- CHARS = [ "." , "." , "." , "1" , "1" , "1" , "1" , "1" , "0" , "0" , "0" ]
4
+ CHARS = "00011111..."
5
5
6
6
# Convert pixels to a string of ASCII characters
7
- def pixels_to_ascii (image ):
8
- pixels = image .convert ("L" ).getdata ()
7
+ def pixels_to_ascii (image , contrast_factor ):
8
+ image = image .convert ("L" )
9
+ enhancer = ImageEnhance .Contrast (image )
10
+ image = enhancer .enhance (contrast_factor )
11
+ pixels = image .getdata ()
9
12
characters = " " .join ([CHARS [int ((pixel / 256 )* len (CHARS ))] for pixel in pixels ])
10
13
return (characters )
11
14
@@ -15,8 +18,20 @@ def photoascii():
15
18
try :
16
19
image = Image .open (path )
17
20
except Exception :
18
- print ("Invalid path " )
21
+ print ("Invalid Path! " )
19
22
return
23
+
24
+ contrast_factor = input ("Enter contrast factor (1 = Original Contrast) [Note: Enter negative value to invert output] : " )
25
+ try :
26
+ contrast_factor = float (contrast_factor )
27
+ except Exception :
28
+ print ("Invalid Input!" )
29
+ return
30
+
31
+ if contrast_factor < 0 :
32
+ global CHARS
33
+ CHARS = CHARS [::- 1 ]
34
+ contrast_factor = - contrast_factor
20
35
21
36
# Fetch the name of the image file
22
37
dot_index = path .rfind ('.' )
@@ -33,7 +48,7 @@ def photoascii():
33
48
resized_image = image .resize ((new_width , new_height ))
34
49
35
50
# Convert image to ASCII
36
- new_image_data = pixels_to_ascii (resized_image )
51
+ new_image_data = pixels_to_ascii (resized_image , contrast_factor )
37
52
pixel_count = len (new_image_data )
38
53
scanline_width = new_width * 2 ;
39
54
ascii_image = "\n " .join ([new_image_data [index :(index + scanline_width )]
0 commit comments