Skip to content

Commit e1cfb06

Browse files
Merge pull request #1618 from aryanrai2001/Photo-To-ASCII-Contrast-and-Inversion
Added contrast and inversion to Photo to ASCII
2 parents 248be26 + 014347d commit e1cfb06

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

Photo To Ascii/photo_to_ascii.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
from PIL import Image
1+
from PIL import Image, ImageEnhance
22

33
# ASCII characters used to build the output text
4-
CHARS = [".", ".", ".", "1", "1", "1", "1", "1", "0", "0", "0"]
4+
CHARS = "00011111..."
55

66
# 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()
912
characters = " ".join([CHARS[int((pixel/256)*len(CHARS))] for pixel in pixels])
1013
return(characters)
1114

@@ -15,8 +18,20 @@ def photoascii():
1518
try:
1619
image = Image.open(path)
1720
except Exception:
18-
print("Invalid path")
21+
print("Invalid Path!")
1922
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
2035

2136
# Fetch the name of the image file
2237
dot_index = path.rfind('.')
@@ -33,7 +48,7 @@ def photoascii():
3348
resized_image = image.resize((new_width, new_height))
3449

3550
# Convert image to ASCII
36-
new_image_data = pixels_to_ascii(resized_image)
51+
new_image_data = pixels_to_ascii(resized_image, contrast_factor)
3752
pixel_count = len(new_image_data)
3853
scanline_width = new_width * 2;
3954
ascii_image = "\n".join([new_image_data[index:(index+scanline_width)]

0 commit comments

Comments
 (0)