Skip to content

Instantly share code, notes, and snippets.

@Who23
Created December 22, 2018 02:36
Show Gist options
  • Save Who23/35875826d539f6fbf496071c6a62de23 to your computer and use it in GitHub Desktop.
Save Who23/35875826d539f6fbf496071c6a62de23 to your computer and use it in GitHub Desktop.
takes an image and renders it in a terminal when run in a terminal (256 color)
from PIL import Image
import sys
COLOR_DIFF = (0, 95, 135, 175, 215, 255)
imageNM = input("Image?: ")
SCALING = int(input("Scale? (5 - high, 20 - low): "))
im = Image.open(imageNM, "r")
width, height = im.size
pixels = list(im.getdata())
buckets = []
def get256color(rgbTuple):
#converts 'true color' to xterm-256 color number.
newRGB = []
#check for greys/black/white on grey scale ramp
if (rgbTuple[0]-10 <= rgbTuple[1] and rgbTuple[1] <= rgbTuple[0]+10 and #red is close to green
rgbTuple[1]-10 <= rgbTuple[2] and rgbTuple[2] <= rgbTuple[1]+10 and #green is close to blue
rgbTuple[0]-10 <= rgbTuple[2] and rgbTuple[2] <= rgbTuple[0]+10): #red is close to blue
avgGrey = (rgbTuple[0] + rgbTuple[1] + rgbTuple[2])/3
if avgGrey < 4:
return 0
elif avgGrey > 246:
return 255
elif int(avgGrey/10) == 24:
return 255
return 232+int(avgGrey/10)
#regular colors
for val in rgbTuple:
for index, item in enumerate(COLOR_DIFF):
if item == 255 or (item <= val and val < COLOR_DIFF[index+1]):
if item == 255:
newRGB.append(5)
break
if abs(val - item) < abs(val - COLOR_DIFF[index+1]):
newRGB.append(index)
break
else:
newRGB.append(index+1)
break
return 16+(36*newRGB[0])+(6*newRGB[1])+newRGB[2]
for y in range(int(height/SCALING)):
buckets.append([])
for x in range(int(width/SCALING)):
buckets[y].append([])
for y in range(height):
for x in range(width):
try:
buckets[int(y/SCALING)-1][int(x/SCALING)-1].append(pixels[width*y+x])
except IndexError:
print("IndexError")
print(int(y/SCALING), int(x/SCALING), y, x)
print(len(buckets), len(buckets[0]))
quit()
for row in buckets:
for index, column in enumerate(row):
r = 0
g = 0
b = 0
c = 0
for pixel in column:
r += pixel[0]
g += pixel[1]
b += pixel[2]
c += 1
newColumn = get256color((int(r/c), int(b/c), int(b/c)))
sys.stdout.write("\033[48;5;" + str(newColumn) + "m ")
sys.stdout.write("\033[0m\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment