完整教學
github
環境設定
1 2 3 4
| import os import sys import cv2 from PIL import Image
|
要記得安裝ffmpeg呦~不然OpenCV會打不開很多影片文件格式
提醒!此程式碼要改原始影片位置的,所以要先弄清楚影片位置要改什麼喔!
(因為我是用vscode內終端機去跑的所以我就要輸入完整的影片位置,例如:/Users/admin/desktop/….等)
完整程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import os import sys import cv2 from PIL import Image
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
def resized_gray_image(image ,new_width=70): width,height = image.size aspect_ratio = height/width new_height = int(aspect_ratio * new_width) resized_gray_image = image.resize((new_width,new_height)).convert('L') return resized_gray_image
def pix2chars(image): pixels = image.getdata() characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels]) return characters
def generate_frame(image,new_width=70): new_image_data = pix2chars(resized_gray_image(image))
total_pixels = len(new_image_data)
ascii_image = "\n".join([new_image_data[index:(index+new_width)] for index in range(0, total_pixels, new_width)])
sys.stdout.write(ascii_image) os.system('cls' if os.name == 'nt' else 'clear')
cap = cv2.VideoCapture("影片.mp4")
while True:
ret,frame = cap.read() cv2.imshow("frame",frame) generate_frame(Image.fromarray(frame)) cv2.waitKey(1)
|