def p2a(filename): fp = open(filename) image = Image.open(fp).convert('L') screen = aalib.AsciiScreen(width=100, height=image.size[1]*45/image.size[0]) image=image.resize(screen.virtual_size) screen.put_image((0, 0), image) return screen.render()
def index(request): screen = aalib.AsciiScreen(width=234, height=120) if request.method == 'POST': uploaded_file = request.FILES['uploaded_file'] image = PIL.Image.open(uploaded_file, 'r').convert('L').resize(screen.virtual_size) #image = PIL.Image.open('lena.jpg','r').convert('L') else: image = PIL.Image.open('lena.jpg', 'r').convert('L').resize(screen.virtual_size) #screen = aalib.AsciiScreen() #image = PIL.Image.open('lena.jpg','r').convert('L').resize(screen.virtual_size) screen.put_image((0, 0), image) print(screen.virtual_size) #img = PIL.Image.new('RGB',(int(screen.virtual_size[0]*3),screen.virtual_size[1]*4), color=(0,0,0)) img = PIL.Image.new('RGB', (1410, 1800), color=(0, 0, 0)) d = PIL.ImageDraw.Draw(img) d.text((0, 0), screen.render(), fill=(255, 255, 255), align='center') name = str(uuid.uuid4()) + '.png' img.save('static/' + name, 'png') image_data = open("static/" + name, "rb").read() data = {'url': ('/static/' + name)} #return HttpResponse(image_data, content_type="image/png") return JsonResponse(data)
def create_ascii_video_2(): #Extract the image size: image_width, image_height =calculate_image_size_from_video () #Extract the number of rows and length of the string in pixels which is used for the image being #created based on the width and height of the text. how_many_rows, new_img_width = calculate_image_size_from_video_2 () vc = cv2.VideoCapture(videofilename) saved_file_name="" frame_rate=str (vc.get(cv2.cv.CV_CAP_PROP_FPS)) #Png file name counter c=0 if vc.isOpened(): rval , frame = vc.read() else: rval = False while rval: rval, frame = vc.read() #Check to see if file is a valid image. I notice the last frame of the video is an empty file at times: try: myimage= Image.fromarray(frame) except (TypeError, AttributeError): print ("cannot identify image while loop in function create_ascii_video_2", myimage) continue aalib_screen_width= int(image_width/25.28)*img_new_magnitude aalib_screen_height= int(image_height/41.39)*img_new_magnitude screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height ) myimage= Image.fromarray(frame).convert("L").resize(screen.virtual_size) screen.put_image((0,0), myimage) img=Image.new("RGBA", (new_img_width, how_many_rows*fontsize),(120,20,20)) draw = ImageDraw.Draw(img) y = 0 for lines in screen.render().splitlines(): draw.text( (0,y), lines, (255,255,0),font=font ) y = y + fontsize imagefit = ImageOps.fit(img, (image_width, image_height), Image.ANTIALIAS) imagefit.save(str(c)+'.png', "PNG") c = c + 1 cv2.waitKey(1) vc.release() cv2.destroyAllWindows() subprocess.call(["./ffmpeg/ffmpeg", "-i", "%d.png", "-r", frame_rate, "-y", "-c:v", "libx264", "-preset", "slow", "-crf", "18", "-c:a", "copy", "-pix_fmt", "yuv420p", "output.mkv" ]) clean_up(c)
def create_ascii_image(): myimage= Image.open(videofilename) image_width, image_height = myimage.size aalib_screen_width= int(image_width/24.9)*img_new_magnitude aalib_screen_height= int(image_height/41.39)*img_new_magnitude screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height ) myimage= Image.open(videofilename).convert("L").resize(screen.virtual_size) screen.put_image((0,0), myimage) y = 0 how_many_rows = len ( screen.render().splitlines() ) new_img_width, font_size = font.getsize (screen.render().splitlines()[0]) img=Image.new("RGBA", (new_img_width, how_many_rows*fontsize),(120,20,20)) draw = ImageDraw.Draw(img) for lines in screen.render().splitlines(): draw.text( (0,y), lines, (255,255,0),font=font ) y = y + fontsize imagefit = ImageOps.fit(img, (image_width, image_height), Image.ANTIALIAS) imagefit.save("ascii_photo.png", "PNG")
def __init__(self): height, width = self.get_terminal_size() self.screen = aalib.AsciiScreen(height=height, width=width) # init tty attributes self._tty_settings = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno())
def test_aalib_put_image(): screen = aalib.AsciiScreen(width=120, height=40) img = Image.open('test.jpg').convert('L').resize(screen.virtual_size) start_time = time.time() for i in range(20): screen.put_image((0,0), img) print('screen put image: %.06f' % ((time.time() - start_time) / 20.0)) screen.close()
def __to_ascii__(self, f): screen = aalib.AsciiScreen(width=self.__width, height=self.__height) image = PIL.Image.open(f).convert("L").resize(screen.virtual_size) screen.put_image((0, 0), image) return screen.render()
def __init__(self): try: self.tp = printer.Usb(0x1a86, 0x7584, interface=0, in_ep=2, out_ep=2) except: print('cannot open thermal printer!') self.screen = aalib.AsciiScreen(width=32, height=12)
def prepare_media(self, out, media, name, image_name, read, mess_id, color, date): if media is not None: if hasattr(media, 'photo') and self.aalib: try: if not os.path.isfile(os.getcwd() + "/downloads/" + str(media.photo.id) + ".jpg"): # download picture client.download_media( media, "downloads/" + str(media.photo.id)) max_width = int((self.width - len(image_name) - 11) / 1.3) max_height = int((self.height - 12) / 1.3) screen = aalib.AsciiScreen(width=max_width, height=max_height) image = Image.open(os.getcwd() + "/downloads/" + str(media.photo.id) + ".jpg").convert('L').resize( screen.virtual_size) screen.put_image((0, 0), image) image_text = screen.render() image_text = image_text.split("\n") for k in range(len(image_text) - 1, 0, -1): out.append( self.Messages( len(image_name) * " ", date, color, image_text[k], mess_id, read)) out.append( self.Messages(image_name, date, color, image_text[0], mess_id, read)) except: out.append( self.Messages(image_name, date, color, "<Unknown photo>", mess_id, read)) elif hasattr(media, 'photo') and not self.aalib: out.append( self.Messages(name, date, color, "<Image>", mess_id, read)) elif hasattr(media, 'document'): try: # print sticker like a emoji if hasattr(media.document.attributes[1], 'stickerset'): out.append( self.Messages( name, date, color, "Sticker: " + media.document.attributes[1].alt, mess_id, read)) except: out.append( self.Messages(name, date, color, "<Document>", mess_id, read))
def handle_AABOOBIES(self, msgtype, user, recip, cmd): #{{{ width = 60 height = 30 (url, bid) = self.factory.db_getRandomBoobies() screen = aalib.AsciiScreen(width=width, height=height) fp = StringIO(urllib2.urlopen(url).read()) image = Image.open(fp).convert('L').resize(screen.virtual_size) screen.put_image((0, 0), image) output = screen.render() out_arr = output.split() for i in xrange(height): self.sendMessage(msgtype, user, recip, out_arr[i])
def handle_AABOOBIES(self, req): #{{{ if not use_aalib: self.sendReply(req, "Sorry, this platform does not support aalib :(") else: width = 60 height = 30 (url, bid) = self.factory.db.getRandomBoobies() screen = aalib.AsciiScreen(width=width, height=height) fp = StringIO(urllib2.urlopen(url).read()) image = Image.open(fp).convert('L').resize(screen.virtual_size) screen.put_image((0, 0), image) output = screen.render() out_arr = output.split() for i in xrange(height): self.sendReply(req, out_arr[i])
def turn_image(self, url): self.self.backup_state() import aalib from PIL import Image from cStringIO import StringIO self.update_status(u'正在载入...') cols, rows = DTerm.loop.screen.get_cols_rows() (head_rows, foot_rows), (orig_head, orig_foot) = self.home.frame_top_bottom( (cols, rows), False) rows -= head_rows + foot_rows r = self.forum.session.get(url) fp = StringIO(r.content) image = Image.open(fp).convert('L') origin_width, origin_height = image.size origin_width = origin_width * 2 width_ratio = float(origin_width) / cols height_ratio = float(origin_height) / rows ratio = width_ratio if width_ratio > height_ratio else height_ratio width = int(origin_width / ratio) height = int(origin_height / ratio) screen = aalib.AsciiScreen(width=width, height=height) image = image.resize(screen.virtual_size) screen.put_image((0, 0), image) self.update_status(u'载入完成') widget = urwid.Filler( urwid.Padding(urwid.Text(screen.render()), align="center", width="pack")) self.state = "image" self.home.body = widget
def _render_img(self): """ Return the rendered image. """ screen = aalib.AsciiScreen(width=self._img_width, height=self._img_height) image = self._image.resize(screen.virtual_size) screen.put_image((0, 0), image) menu_contrast = self._menu["contrast"]["value"] menu_brightness = self._menu["brightness"]["value"] menu_gamma = self._menu["gamma"]["value"] menu_invert = self._menu["invert"]["value"] menu_dithering = self._menu["dithering"]["value"] menu_random_dither = self._menu["random"]["value"] return screen.render(contrast=menu_contrast, brightness=menu_brightness, gamma=menu_gamma / 255, dithering_mode=menu_dithering, inversion=menu_invert, random=menu_random_dither)
def calculate_image_size_from_video_2 (): #Extract the image size: image_width, image_height =calculate_image_size_from_video () vc = cv2.VideoCapture(videofilename) if vc.isOpened(): rval , frame = vc.read() else: rval = False while rval: rval, frame = vc.read() #Check to see if file is a valid image. I notice the last frame of the video is an empty file at times: try: myimage= Image.fromarray(frame) except (TypeError, AttributeError): print ("cannot identify image", myimage) continue aalib_screen_width= int(image_width/25.28)*img_new_magnitude aalib_screen_height= int(image_height/41.39)*img_new_magnitude screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height ) myimage= Image.fromarray(frame).convert("L").resize(screen.virtual_size) screen.put_image((0,0), myimage) how_many_rows = len ( screen.render().splitlines() ) new_img_width, font_size = font.getsize (screen.render().splitlines()[0]) cv2.waitKey(1) vc.release() return (how_many_rows, new_img_width )
def ascii_lines_generator(image_name, height, width): screen = aalib.AsciiScreen(width=width, height=height) image = Image.open(image_name).convert('L').resize(screen.virtual_size) screen.put_image((0, 0), image) for line in screen.render().split('\n'): yield line
def __init__(self): self.tp = printer.Usb(0x1a86, 0x7584, interface=0, in_ep=2, out_ep=2) self.screen = aalib.AsciiScreen(width=32, height=12)
import io import urllib2 import PIL.Image import aalib screen = aalib.AsciiScreen(width=80, height=40) fp = io.BytesIO( urllib2.urlopen('https://www.python.org/static/favicon.ico').read()) image = PIL.Image.open(fp).convert('L').resize(screen.virtual_size) screen.put_image((0, 0), image) print screen.render()
import io, time import picamera from PIL import Image import aalib screen = aalib.AsciiScreen(width=120, height=39) camera = picamera.PiCamera() #while True: contrast = 0 contrast_step = 4 while True: start_time = time.time() stream = io.BytesIO() camera.resolution = (256, 144) camera.capture(stream, format='jpeg', use_video_port=True) stream.seek(0) image = Image.open(stream).convert('L').resize(screen.virtual_size) stream.close() screen.put_image((0, 0), image) print(screen.render(contrast=contrast)) print("time: %.06f contrast: %d" % (time.time() - start_time, contrast)) if (contrast + contrast_step) < 0 or (contrast + contrast_step) > 127: contrast_step = -1 * contrast_step contrast += contrast_step screen.close()
import aalib import Image # parameters optimized to a specific screen res = {'width': 120, 'height': 40} origin = (30, 0) screen = aalib.AsciiScreen(width=res['width'], height=res['height']) image = Image.open('test.jpg').convert('L').resize(screen.virtual_size) screen.put_image(origin, image) print screen.render()
#!/usr/bin/python import aalib import Image import os columnnum = 100 linenum = 30 timenum = 40 screen = aalib.AsciiScreen( width=columnnum,height=linenum ) ''' out = open('xx1_bin.txt','w') i = 0 while True: i += 1 filename = 'xx1_bin/%s.bmp' % str(i) if not os.path.isfile(filename) : break print i image = Image.open(filename).convert('L').resize(screen.virtual_size) screen.put_image((0,0),image) out.write(screen.render()) out.write('\n') ''' out = open('xx1_color.txt','w') i = 0
from PIL import Image import aalib ap = argparse.ArgumentParser(description='Convert image to ASCII art') ap.add_argument('-c', '--columns', default=80, type=int, help='Display width in characters') ap.add_argument('-r', '--rows', default=40, type=int, help='Display height in characters') ap.add_argument('url', metavar='URL', nargs=1, help='the URL to read the image from') args = ap.parse_args() screen = aalib.AsciiScreen(width=args.columns, height=args.rows) res = urllib.request.urlopen(args.url[0]) raw = io.BytesIO(res.read()) image = Image.open(raw).convert('L').resize(screen.virtual_size) screen.put_image((0, 0), image) print(screen.render())
# 0 es para agarrar cualquier device. cam = cv2.VideoCapture(0) cam.set(3, 1024) cam.set(4, 720) if cam.isOpened(): rval, image = cam.read() else: rval = False tSize = getTerminalSize() size = (tSize[0] - 1, tSize[1] - 1) screen = aalib.AsciiScreen(width=size[1], height=size[0]) w = int(cam.get(3)) # CV_CAP_PROP_FRAME_WIDTH h = int(cam.get(4)) # CV_CAP_PROP_FRAME_HEIGHT scr = curses.initscr() bvalue = 1 cvalue = 1 gvalue = 1.3 gvalueStep = 0.05 cvalueStep = 1 while rval: try: cv2.imshow('frame', image) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.resize(image, (screen.virtual_size))
term_size = sp.check_output('stty size', shell=True).decode('utf-8') term_size = term_size.split(' ') term_size = (int(term_size[0]), int(term_size[1])) aalib_screen_height = int(term_size[0] * 0.95) aalib_screen_width = int(term_size[1] * 0.47) print(aalib_screen_height, aalib_screen_width) game_dir = sys.argv[1] for d in os.listdir(game_dir): for jpg in os.listdir(game_dir + "/" + d + "/animations"): if ".jpg" in jpg: with open(game_dir + "/" + d + "/animations/" + jpg, 'rb') as f: screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height) raw_image = PIL.Image.open(f).convert('L').resize( screen.virtual_size) #inverted=PIL.ImageOps.invert(raw_image) screen.put_image((0, 0), raw_image) new_ascii = screen.render() txt_file = os.path.splitext(jpg)[0] + '.txt' with open(game_dir + "/" + d + "/animations/" + txt_file, 'w') as output: output.write(new_ascii)
import cv2 from PIL import Image import aalib from console import get_terminal_size import time h, w = get_terminal_size() screen = aalib.AsciiScreen(width=w, height=h) vc = cv2.VideoCapture(0) print('Ascii Screen initialized:', screen) print('CV2 initialized:', vc) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False print('Camera is not opened', vc.isOpened()) while rval: rval, frame = vc.read() frame = cv2.cvtColor( frame, cv2.COLOR_BGR2RGB) # convert opencv default GBR to RGB height, width = (frame.shape[0], frame.shape[1]) # pixel size image = Image.fromstring('RGB', (width, height), frame.tostring()) screen.put_image((0, 0), image.convert('L').resize(screen.virtual_size)) print(screen.render(contrast=70)) time.sleep(0.01) key = cv2.waitKey(20)
def printLogo(logo_url): screen = aalib.AsciiScreen(width=SCREEN_WIDTH, height=SCREEN_HEIGHT) logo = io.BytesIO(requests.get(logo_url).content) image = PIL.Image.open(logo).convert('L').resize(screen.virtual_size) screen.put_image((0, 0), image) print(screen.render())