Last active
September 5, 2017 15:27
-
-
Save evanxg852000/06f32f2084852917cd81efa2a1cb552a to your computer and use it in GitHub Desktop.
Convert image to txt file representation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
def getStr(grayscale): | |
if (grayscale >= 230.0): | |
return ' ' | |
if (grayscale >= 200.0): | |
return '.' | |
if (grayscale >= 180.0): | |
return '*' | |
if (grayscale >= 160.0): | |
return ':' | |
if (grayscale >= 130.0): | |
return 'o' | |
if (grayscale >= 100.0): | |
return '&' | |
if (grayscale >= 70.0): | |
return '8' | |
if (grayscale >= 50.0): | |
return '#' | |
return '@' | |
def getInverseStr(grayscale): | |
if (grayscale >= 230.0): | |
return '@' | |
if (grayscale >= 200.0): | |
return '#' | |
if (grayscale >= 180.0): | |
return '8' | |
if (grayscale >= 160.0): | |
return '&' | |
if (grayscale >= 130.0): | |
return 'o' | |
if (grayscale >= 100.0): | |
return ':' | |
if (grayscale >= 70.0): | |
return '*' | |
if (grayscale >= 50.0): | |
return '.' | |
return ' ' | |
def convertImage(str, w=140, h=140): | |
im = Image.open(str, 'r') | |
im.thumbnail((w, h)) | |
width, height = im.size | |
data = list(im.getdata()) | |
textImage = '' | |
negative = True | |
for (idx, pix) in enumerate(data): | |
if (idx % width == 0) : | |
textImage +='\n' | |
grayscale = pix[0] * 0.2989 + pix[1] * 0.5870 + pix[2] * 0.1140 | |
textImage += getInverseStr(grayscale) if negative else getStr(grayscale) | |
file = open('out.txt','w') | |
file.write(textImage) | |
file.close() | |
def main(): | |
convertImage('1200px-Alessandro_Del_Piero_in_2014.jpg') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment