Today I will be showing you how to convert video to ASCII text in Python and Tkinter. This uses the PIL module, cv2 module, and Tkinter module and allows you to convert video to ASCII and play it in a Tkinter window, it uses a Tkinter textbox to show the ASCII text version. The code is fairly simple and easy to use. Since I couldn’t find a better tutorial on doing this I decided to make a tutorial myself! Enjoy!
Code is below (with comments) for you to view and copy.
#Created by Flynn's Forge 2021, from https://flynnsforge.com/ #Imports import sys import PIL.Image from tkinter import * import cv2 root = Tk() root.option_add('*Font', 'Times 1') #setting font to small so the video fits into the screen text = Text(root) text.pack(expand='true', fill=BOTH) detail = 83 def update_detail(event): #changes video detail global detail detail = w.get() print(detail) w = Scale(root, from_=30, to=200, orient=HORIZONTAL, command=update_detail) #create slider to change detail w.pack() def generate_from_video(): # get image and read it video_path = "yourvideo.mp4" #add path to your mp4 file here cap = cv2.VideoCapture(video_path) if cap.isOpened(): framerate = cap.get(cv2.CAP_PROP_FPS) framecount = 0 while(True): # capture frame-by-frame success, image = cap.read() img = PIL.Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) # resize the image width, height = img.size aspect_ratio = height/width new_width = width new_height = aspect_ratio * new_width * 0.55 img = img.resize((new_width, int(new_height))) # convert image to greyscale format img = img.convert('L') pixels = img.getdata() #convert to ASCII chars = ["B","S","#","&","@","$","%","*","!",":","."] #values taken from https://pythoncircle.com new_pixels = [chars[pixel//detail] for pixel in pixels] new_pixels = ''.join(new_pixels) new_pixels_count = len(new_pixels) ascii_image = [new_pixels[index:index + new_width] for index in range(0, new_pixels_count, new_width)] ascii_image = "\n".join(ascii_image) #show in Tkinter text.delete('1.0', END) text.insert(1.0, ascii_image) text.update() else: print("Not Opened!") generate_from_video() root.mainloop()
The code displaying a clip from one of my Youtube Videos
So how does this work? Well, we simply use cv2 to grab each frame from the video, convert it to ASCII and then insert it into the Tkinter text box! You can change the detail with the slider to see what works best. NOTE: Not all videos will work with this, certain formats may not work and things like 4K video will most likely lag, certain video sizes may be too big to appear on the screen. Anyway, I hope you enjoyed this tutorial! Please check out my youtube channel for more tutorials! Also, check out my other tutorials here.