Skip to content

Instantly share code, notes, and snippets.

@sooop
Last active May 12, 2021 07:43
Show Gist options
  • Save sooop/571ad16abe27ae20f5a693d72ab6aa8e to your computer and use it in GitHub Desktop.
Save sooop/571ad16abe27ae20f5a693d72ab6aa8e to your computer and use it in GitHub Desktop.
Convert Image to Braille Unicode text (using PIL)
'''Convert image to braille text'''
import argparse
from PIL import Image
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--th", default=127, type=int, dest="threadh")
parser.add_argument("-w", "--width", default=120, type=int, dest="width")
parser.add_argument("-s", "--scale", default=1.0, type=float, dest="scale")
parser.add_argument(
"-i", "--invert", action="store_true", dest="invert"
)
parser.add_argument('file' )
return parser.parse_args()
def convert(imgfile: str, width=160, scale=1.0, cutoff=127, invert=False) -> str:
res: list[str] = []
# load image
im_src = Image.open(imgfile)
WIDTH = int(width * scale)
HEIGHT = int(WIDTH / im_src.width * im_src.height)
# create black/white image
im_res: Image.Image = (
im_src.convert("L")
.resize((WIDTH, HEIGHT), resample=Image.HAMMING)
.point(lambda x: x > cutoff if invert else x < cutoff, mode="1")
)
# check every pixel (row step: 4, col step: 2)
for row in range(0, im_res.height, 4):
line: list[str] = []
for col in range(0, im_res.width, 2):
val, i = 0, 0
for c_pos in range(0, 2):
for r_pos in range(0, 4):
if col + c_pos < im_res.width and row + r_pos < im_res.height:
p = im_res.getpixel((col + c_pos, row + r_pos))
else:
p = 0
if p > 0:
val += 1 << i
i += 1
line.append(chr(0x2800 + val))
res.append("".join(line))
return "\n".join(res)
if __name__ == '__main__':
args = parse_args()
print(convert(args.file, args.width, args.scale, args.threadh, args.invert))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment