asciifier

Script to turn images into ASCII art
git clone git@git.mcdim.xyz:/var/www/git/asciifier.git
Log | Files | Refs

asciier.py (1967B)


      1 import os
      2 import sys
      3 import cv2
      4 import numpy as np
      5 from math import sqrt
      6 from PIL import Image
      7 
      8 
      9 # Get image fele name #
     10 
     11 if( len(sys.argv) >= 2 ):
     12 	image_name = sys.argv[1]
     13 else:
     14 	print("Terminated")
     15 	exit(0)
     16 
     17 
     18 # Get columns/rows #
     19 
     20 rows, columns = os.popen('stty size', 'r').read().split()
     21 print(columns)
     22 print(rows)
     23 
     24 
     25 # Set values #
     26 
     27 v0 = " "
     28 v1 = "-"
     29 v2 = "="
     30 v3 = ":"
     31 v4 = "%"
     32 v5 = "@"
     33 v6 = "#"
     34 
     35 
     36 # Convert to bw #
     37 
     38 bilevel = False
     39 
     40 if bilevel:
     41 	imagef = Image.open(image_name)
     42 	imagef = imagef.convert('1')
     43 	imagef.save('result.png')	
     44 else:
     45 	imagef = Image.open(image_name)
     46 	thresh = 1 
     47 	fn = lambda x : 255 if x > thresh else 0
     48 	r = imagef.convert('L').point(fn, mode='1')
     49 	r.save('result.png')
     50 
     51 img = cv2.imread('result.png')
     52 width, height, lol = img.shape
     53 iteri = height / int(rows)
     54 iteri = int(iteri)
     55 iteri = iteri
     56 for r in range(0,img.shape[0],iteri):
     57 	print("\n", end="")
     58 	for c in range(0,img.shape[1],int(iteri-(iteri*40/100))):
     59 #for c in range(0,img.shape[1],int(iteri)):
     60 #	print("\n}", end="")
     61 #	for r in range(0,img.shape[0],int(iteri)):
     62 		myimg = img[r:r+int(iteri), c:c+int(iteri),:]
     63 		#cv2.imwrite(f"img{r}_{c}.png",img[r:r+30, c:c+30,:])
     64 		avg_color_per_row = np.average(myimg, axis=0)
     65 		avg_color = np.average(avg_color_per_row, axis=0)
     66 		#print(avg_color)
     67 		R,G,B= avg_color
     68 		value = (R+G+B)/3
     69 		#print(value, end =" ")
     70 
     71 		st = True
     72 		if st:
     73 			if value < 1:
     74 				print(v0, end ="")
     75 			elif value < 5:
     76 				print(v1, end ="")
     77 			elif value < 10:
     78 				print(v2, end ="")
     79 			elif value < 25:
     80 				print(v3, end ="")
     81 			elif value < 35:
     82 				print(v4, end ="")
     83 			elif value < 40:
     84 				print(v5, end ="")
     85 			else:
     86 				print(v6, end ="")
     87 		else:
     88 	
     89 			if value < 1:
     90 				print("#", end ="")
     91 			elif value < 5:
     92 				print("@", end ="")
     93 			elif value < 10:
     94 				print("%", end ="")
     95 			elif value < 25:
     96 				print(":", end ="")
     97 			elif value < 35:
     98 				print("=", end ="")
     99 			elif value < 40:
    100 				print("-", end ="")
    101 			else:
    102 				print(" ", end ="")
    103 print("\n")