Advertisement
Jobjob

ASCII ART - Python

Aug 6th, 2013
501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.22 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. """
  4.    Version 1.0
  5.    Code by Delplanque Julien.
  6.    This website help me to understand how the algorithm of conversion work : http://mattmik.com/articles/ascii/ascii.html
  7. """
  8.  
  9. import umage
  10. import copy
  11. import platform
  12. import os
  13. import sys
  14.  
  15. COLOURS = {
  16.     "default"    :    "\033[0m",
  17.     # style
  18.     "bold"       :    "\033[1m",
  19.     "underline"  :    "\033[4m",
  20.     "blink"      :    "\033[5m",
  21.     "reverse"    :    "\033[7m",
  22.     "concealed"  :    "\033[8m",
  23.     # text colors
  24.     "black"      :    "\033[30m",
  25.     "red"        :    "\033[31m",
  26.     "green"      :    "\033[32m",
  27.     "yellow"     :    "\033[33m",
  28.     "blue"       :    "\033[34m",
  29.     "magenta"    :    "\033[35m",
  30.     "cyan"       :    "\033[36m",
  31.     "white"      :    "\033[37m",
  32.     # font colors
  33.     "on_black"   :    "\033[40m",
  34.     "on_red"     :    "\033[41m",
  35.     "on_green"   :    "\033[42m",
  36.     "on_yellow"  :    "\033[43m",
  37.     "on_blue"    :    "\033[44m",
  38.     "on_magenta" :    "\033[45m",
  39.     "on_cyan"    :    "\033[46m",
  40.     "on_white"   :    "\033[47m" }
  41.  
  42. def style(key):
  43.     """
  44.        Change the style of the output in the shell.
  45.    """
  46.     if (platform.system() != "Windows"):
  47.         sys.stdout.write(COLOURS[key])
  48.    
  49. def brightness(R,G,B):
  50.     """
  51.        Return the brightness of a RGB triplet.
  52.    """
  53.     return (R+G+B)/3
  54.  
  55. def chooseCharacter(x,characterSet=['#','@','$','%','x','o','l','i','=','+','<','*','^','~','\"','|',';','-',',','.']):
  56.     """
  57.        Choose a character in the character set according to the brightness x in parameter.
  58.    """
  59.     y = 255/len(characterSet)
  60.     a = len(characterSet)
  61.     b = a-1
  62.     while(b>=0):
  63.         if x<a*y and x >= b*y:
  64.             return characterSet[b]
  65.         else:
  66.             a-=1
  67.             b-=1
  68.  
  69. def convert(img, step=3):
  70.     """
  71.        Convert a matrix of RGB triplet into a matrix of characters according to the brightness of each pixel.
  72.    """
  73.     image = copy.deepcopy(img)
  74.     mat = []
  75.     for i in range(0,len(image),step):
  76.         matb = []
  77.         for j in range(0,len(image[0]),step):
  78.             bri = 0
  79.             for k in range(i,i+step):
  80.                 for l in range(j,j+step):
  81.                     try:
  82.                         R,G,B = image[k][l][0],image[k][l][1],image[k][l][2]
  83.                     except IndexError:
  84.                         R,G,B = 0,0,0
  85.                     bri += brightness(R,G,B)/(step**2)
  86.             s = chooseCharacter(bri)
  87.             matb.append(s)
  88.         mat.append(matb)
  89.     return mat
  90.  
  91. def convertToString(mat):
  92.     """
  93.        Convert a matrix that contains string into a string.
  94.    """
  95.     s = ""
  96.     for i in range(len(mat)):
  97.         for j in range(len(mat[0])):
  98.             try:
  99.                 s += mat[i][j]
  100.             except TypeError:
  101.                 pass
  102.         s += "\n"
  103.     return s
  104.  
  105. def question(s):
  106.     """
  107.        Ask the question in parameter and return True or False according to the user's choice (yes or no).
  108.    """
  109.     f = True
  110.     while(f):
  111.         style("magenta")
  112.         r = raw_input(s+" (Y/n)")
  113.         style("default")
  114.         if(r == "" or r == "y" or r == "yes"):
  115.             return True
  116.         elif(r == "n" or r == "no"):
  117.             return False
  118.            
  119. def error(message):
  120.     """
  121.        Display the error message in parameter.
  122.    """
  123.     style("red")
  124.     print message
  125.     style("default")
  126.    
  127. def configuration(inName, outName, precision):
  128.     """
  129.        Display the current configuration according to the parameters.
  130.    """
  131.     if(inName == ""):
  132.         inName = "Not set."
  133.     style("green")
  134.     print "----------Configuration----------\n"
  135.     print "In file name : "+str(inName)
  136.     print "Out file name : "+str(outName)
  137.     print "Precision : "+str(precision)
  138.     print "\n---------------------------------"
  139.     style("default")
  140.  
  141. def help():
  142.     """
  143.        Display the help message.
  144.    """
  145.     style("green")
  146.     print "------------------------------------Help------------------------------------\n"
  147.     print "i or in             Set the input file."
  148.     print "o or out            Set the output file."
  149.     print "p or precision      Set the precision. 1 = highest precision = 1char/pix"
  150.     print "c or configuration  Show the current configuration."
  151.     print "w or write          Write the text file using the current configuration."
  152.     print "h or help           Show this help message."
  153.     print "q or quit           Quit the application."
  154.     print "cls or clear        Clear the screen."
  155.     print "\n----------------------------------------------------------------------------"
  156.     style("default")
  157.  
  158. def clearScreen():
  159.     """
  160.        Clear the string according to the os.
  161.    """
  162.     if platform.system() == "Windows":
  163.         os.system("cls")
  164.     elif platform.system() == "Linux" or os.platform() == "darwin":
  165.         os.system("clear")
  166.     else:
  167.         print "Unknown os, no clear screen for you sorry..."
  168.    
  169. def main():
  170.     style("blue")
  171.     print "------------------------------Image to ascii 1.0----------------------------"
  172.     print "Type h for help."
  173.     style("default")
  174.     inName = ""
  175.     outName = "ascii.txt"
  176.     precision = 3
  177.     f = True
  178.     while(f):
  179.         style("blue")
  180.         s = raw_input("ImToAscii >>> ")
  181.         style("default")
  182.         if(s == "in" or s == "i"):
  183.             inName = raw_input("Enter the name of the input file (.png,.jpg,...) : ")
  184.             if(os.path.isfile(inName) == False):
  185.                 inName=""
  186.                 error("The input file doesn't exists!")
  187.             else:
  188.                 print "Input file set."
  189.         elif(s == "out" or s == "o"):
  190.             outName = raw_input("Enter the name of the output file (.txt) : ")
  191.             txt = outName.find(".txt")
  192.             if(txt == len(outName)-5):
  193.                 print "Output file set."
  194.             elif(txt == -1):
  195.                 outName = outName+".txt"
  196.         elif(s == "precision" or s == "p"):
  197.             pre = raw_input("Enter the precision you want (must be >= 1, actually "+str(precision)+") : ")
  198.             try:
  199.                 temp = int(pre)
  200.                 if(temp >= 1):
  201.                     precision = temp
  202.                 else:
  203.                     error("You must set the precision as an integer >= 1!")
  204.             except ValueError:
  205.                 error("You must set the precision as an integer >= 1!")
  206.         elif(s == "configuration" or s == "c"):
  207.             configuration(inName, outName, precision)
  208.         elif(s == "write" or s == "w"):
  209.             if(inName == ""):
  210.                 error("You must set the input file.")
  211.             else:
  212.                 configuration(inName, outName, precision)
  213.                 b = question("Is that the right configuration?")
  214.                 if(b == True):
  215.                     img = umage.load(inName)
  216.                     m = convert(img,precision)
  217.                     st = convertToString(m)
  218.                     fi = open(outName,"w")
  219.                     fi.write(st)
  220.                     fi.close()
  221.                     print "File successfully writed."
  222.         elif(s == "clear" or s == "cls"):
  223.             clearScreen()
  224.         elif(s == "quit" or s == "q"):
  225.             f = False
  226.         else:
  227.             help()
  228.  
  229. if __name__ == '__main__':
  230.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement