Skip to content

Commit dcdd9ba

Browse files
committed
Refactor image_to_text to reduce nesting depth
1 parent db1b895 commit dcdd9ba

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

src/etc.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
# http://www.pythonchallenge.com/
1111

12+
from itertools import product
1213
from math import sqrt
1314

1415

@@ -24,11 +25,10 @@ def factorize(number):
2425
def image_to_text(image, threshold=10, skip=6, white="##", black=" "):
2526
"""Converts an image to text, lighting pixel greater than a threshold and
2627
skiping some rows/cols"""
27-
image, lines = image.crop(image.getbbox()).convert("L"), []
28-
for y in range(0, image.height, skip):
29-
line = [black] * -(-image.width // skip)
30-
for x in range(0, image.width, skip):
31-
if image.getpixel((x, y)) > threshold:
32-
line[x // skip] = white
33-
lines.append("".join(line))
34-
return "\n".join(filter(str.strip, lines))
28+
image = image.crop(image.getbbox()).convert("L")
29+
cols, rows = -(-image.width // skip), -(-image.height // skip) # ceiling
30+
lines = [[black] * cols for _ in range(rows)]
31+
for (x, y) in product(range(0, image.width, skip), range(0, image.height, skip)):
32+
if image.getpixel((x, y)) > threshold:
33+
lines[y // skip][x // skip] = white
34+
return "\n".join(filter(str.strip, map("".join, lines)))

0 commit comments

Comments
 (0)