Skip to content

Instantly share code, notes, and snippets.

@iamkissg
Last active April 14, 2017 06:06
Show Gist options
  • Save iamkissg/b650d22b870b747044af281fba8149c4 to your computer and use it in GitHub Desktop.
Save iamkissg/b650d22b870b747044af281fba8149c4 to your computer and use it in GitHub Desktop.
Simple Image Converter
#
# Simple Image Converter for some simple usage.
#
__author__ = "Engine"
__date__ = "2017-04-01"
import string
import fire
from PIL import Image
class ImgConverter(object):
"""A simple image converter"""
def rgb2bmap(self, _input, output):
with Image.open(_input) as img:
binary_map = img.convert('1', dither=Image.NONE)
binary_map.save(output)
return True
return False
def img2text(self, _input, output="output.txt", width=80, height=80):
"""Image to text paint"""
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
length = len(ascii_char)
def get_char(r, g, b, alpha=256):
if alpha == 0:
return " "
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
return ascii_char[int(gray * length / (256.0 + 1))]
try:
img = Image.open(_input)
img = img.resize((width, height), Image.NEAREST)
txt = ""
for h in range(height):
for w in range(width):
txt += get_char(*img.getpixel((w, h)))
txt += "\n"
with open(output, "w") as f:
f.write(txt)
return True
except:
return False
# todo: add more conversion
if __name__ == "__main__":
fire.Fire(ImgConverter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment