Skip to content

Instantly share code, notes, and snippets.

@nkanaev
Created March 1, 2017 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkanaev/8649f313c5f88c468fcd6c63606ed674 to your computer and use it in GitHub Desktop.
Save nkanaev/8649f313c5f88c468fcd6c63606ed674 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import sys
from PIL import Image
BRAILLE_OFFSET = 0x2800
def braillify(image_path, threshold):
image = Image.open(image_path).convert('L')
output = []
for y in range(0, int(image.height / 4) * 4, 4):
for x in range(0, int(image.width / 2) * 2, 2):
p1 = image.getpixel((x, y))
p2 = image.getpixel((x, y + 1))
p3 = image.getpixel((x, y + 2))
p4 = image.getpixel((x + 1, y))
p5 = image.getpixel((x + 1, y + 1))
p6 = image.getpixel((x + 1, y + 2))
p7 = image.getpixel((x, y + 3))
p8 = image.getpixel((x + 1, y + 3))
n = 0
n |= int(p1 < threshold)
n |= int(p2 < threshold) << 1
n |= int(p3 < threshold) << 2
n |= int(p4 < threshold) << 3
n |= int(p5 < threshold) << 4
n |= int(p6 < threshold) << 5
n |= int(p7 < threshold) << 6
n |= int(p8 < threshold) << 7
output.append(chr(BRAILLE_OFFSET + n))
output.append('\n')
return ''.join(output)
def main():
if len(sys.argv) < 2:
print('usage: {} /path/to/image [threshold]'.format(sys.argv[0]))
sys.exit(1)
image_path = sys.argv[1]
threshold = 125
if len(sys.argv) == 3:
threshold = int(sys.argv[2])
print(braillify(image_path, threshold))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment