Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Version 1.0
- Code by Delplanque Julien.
- This website help me to understand how the algorithm of conversion work : http://mattmik.com/articles/ascii/ascii.html
- """
- import umage
- import copy
- import platform
- import os
- import sys
- COLOURS = {
- "default" : "\033[0m",
- # style
- "bold" : "\033[1m",
- "underline" : "\033[4m",
- "blink" : "\033[5m",
- "reverse" : "\033[7m",
- "concealed" : "\033[8m",
- # text colors
- "black" : "\033[30m",
- "red" : "\033[31m",
- "green" : "\033[32m",
- "yellow" : "\033[33m",
- "blue" : "\033[34m",
- "magenta" : "\033[35m",
- "cyan" : "\033[36m",
- "white" : "\033[37m",
- # font colors
- "on_black" : "\033[40m",
- "on_red" : "\033[41m",
- "on_green" : "\033[42m",
- "on_yellow" : "\033[43m",
- "on_blue" : "\033[44m",
- "on_magenta" : "\033[45m",
- "on_cyan" : "\033[46m",
- "on_white" : "\033[47m" }
- def style(key):
- """
- Change the style of the output in the shell.
- """
- if (platform.system() != "Windows"):
- sys.stdout.write(COLOURS[key])
- def brightness(R,G,B):
- """
- Return the brightness of a RGB triplet.
- """
- return (R+G+B)/3
- def chooseCharacter(x,characterSet=['#','@','$','%','x','o','l','i','=','+','<','*','^','~','\"','|',';','-',',','.']):
- """
- Choose a character in the character set according to the brightness x in parameter.
- """
- y = 255/len(characterSet)
- a = len(characterSet)
- b = a-1
- while(b>=0):
- if x<a*y and x >= b*y:
- return characterSet[b]
- else:
- a-=1
- b-=1
- def convert(img, step=3):
- """
- Convert a matrix of RGB triplet into a matrix of characters according to the brightness of each pixel.
- """
- image = copy.deepcopy(img)
- mat = []
- for i in range(0,len(image),step):
- matb = []
- for j in range(0,len(image[0]),step):
- bri = 0
- for k in range(i,i+step):
- for l in range(j,j+step):
- try:
- R,G,B = image[k][l][0],image[k][l][1],image[k][l][2]
- except IndexError:
- R,G,B = 0,0,0
- bri += brightness(R,G,B)/(step**2)
- s = chooseCharacter(bri)
- matb.append(s)
- mat.append(matb)
- return mat
- def convertToString(mat):
- """
- Convert a matrix that contains string into a string.
- """
- s = ""
- for i in range(len(mat)):
- for j in range(len(mat[0])):
- try:
- s += mat[i][j]
- except TypeError:
- pass
- s += "\n"
- return s
- def question(s):
- """
- Ask the question in parameter and return True or False according to the user's choice (yes or no).
- """
- f = True
- while(f):
- style("magenta")
- r = raw_input(s+" (Y/n)")
- style("default")
- if(r == "" or r == "y" or r == "yes"):
- return True
- elif(r == "n" or r == "no"):
- return False
- def error(message):
- """
- Display the error message in parameter.
- """
- style("red")
- print message
- style("default")
- def configuration(inName, outName, precision):
- """
- Display the current configuration according to the parameters.
- """
- if(inName == ""):
- inName = "Not set."
- style("green")
- print "----------Configuration----------\n"
- print "In file name : "+str(inName)
- print "Out file name : "+str(outName)
- print "Precision : "+str(precision)
- print "\n---------------------------------"
- style("default")
- def help():
- """
- Display the help message.
- """
- style("green")
- print "------------------------------------Help------------------------------------\n"
- print "i or in Set the input file."
- print "o or out Set the output file."
- print "p or precision Set the precision. 1 = highest precision = 1char/pix"
- print "c or configuration Show the current configuration."
- print "w or write Write the text file using the current configuration."
- print "h or help Show this help message."
- print "q or quit Quit the application."
- print "cls or clear Clear the screen."
- print "\n----------------------------------------------------------------------------"
- style("default")
- def clearScreen():
- """
- Clear the string according to the os.
- """
- if platform.system() == "Windows":
- os.system("cls")
- elif platform.system() == "Linux" or os.platform() == "darwin":
- os.system("clear")
- else:
- print "Unknown os, no clear screen for you sorry..."
- def main():
- style("blue")
- print "------------------------------Image to ascii 1.0----------------------------"
- print "Type h for help."
- style("default")
- inName = ""
- outName = "ascii.txt"
- precision = 3
- f = True
- while(f):
- style("blue")
- s = raw_input("ImToAscii >>> ")
- style("default")
- if(s == "in" or s == "i"):
- inName = raw_input("Enter the name of the input file (.png,.jpg,...) : ")
- if(os.path.isfile(inName) == False):
- inName=""
- error("The input file doesn't exists!")
- else:
- print "Input file set."
- elif(s == "out" or s == "o"):
- outName = raw_input("Enter the name of the output file (.txt) : ")
- txt = outName.find(".txt")
- if(txt == len(outName)-5):
- print "Output file set."
- elif(txt == -1):
- outName = outName+".txt"
- elif(s == "precision" or s == "p"):
- pre = raw_input("Enter the precision you want (must be >= 1, actually "+str(precision)+") : ")
- try:
- temp = int(pre)
- if(temp >= 1):
- precision = temp
- else:
- error("You must set the precision as an integer >= 1!")
- except ValueError:
- error("You must set the precision as an integer >= 1!")
- elif(s == "configuration" or s == "c"):
- configuration(inName, outName, precision)
- elif(s == "write" or s == "w"):
- if(inName == ""):
- error("You must set the input file.")
- else:
- configuration(inName, outName, precision)
- b = question("Is that the right configuration?")
- if(b == True):
- img = umage.load(inName)
- m = convert(img,precision)
- st = convertToString(m)
- fi = open(outName,"w")
- fi.write(st)
- fi.close()
- print "File successfully writed."
- elif(s == "clear" or s == "cls"):
- clearScreen()
- elif(s == "quit" or s == "q"):
- f = False
- else:
- help()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement