Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import os
- import time
- from argparse import ArgumentParser
- import numpy as np
- import cv2
- from numpy.testing._private.utils import tempdir
- from colorparams import color
- def image_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
- dim = None
- (h, w) = image.shape[:2]
- if width is None and height is None:
- return image
- if width is None:
- r = height / float(h)
- dim = (int(w * r), height)
- else:
- r = width / float(w)
- dim = (width, int(h * r))
- resized = cv2.resize(image, dim, interpolation=inter)
- return resized
- def frame_to_ascii_grayscale(img):
- chars = np.asarray(list("@%#*+=-:. "))
- img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
- img = (img / 255.) * (len(chars) - 1)
- out = ""
- out_arr = chars[img.astype(int)]
- for i, r in enumerate(out_arr):
- out += "".join(r) + '\n'
- return out
- def render_frame(ascii_img, terminal_size):
- sys.stdout.write("\033[{}F".format(terminal_size.lines - 2))
- ascii_img = ascii_img.rstrip('\n')
- print(ascii_img)
- parser = ArgumentParser()
- parser.add_argument("-i", "--image", help="path to image file", type=str)
- parser.add_argument("-v", "--video", help="path to video file", type=str)
- parser.add_argument("-c", "--color", help="grayscale or colored output", type=bool)
- args = parser.parse_args()
- if not args.image and not args.video:
- print("Give one of two paths")
- print(parser.print_help())
- exit(-1)
- if args.image and args.video:
- print("Give one of two paths!")
- print(parser.print_help())
- exit(-1)
- terminal_size = os.get_terminal_size()
- os.system('cls' if os.name == 'nt' else 'clear')
- if args.image:
- img = cv2.imread(args.image)
- assert img is not None, "Give a valid path to the image"
- if img.shape[1] > img.shape[0]:
- img = image_resize(img, height=terminal_size.lines - 2)
- else:
- img = image_resize(img, width=terminal_size.width)
- frame = frame_to_ascii_grayscale(img)
- render_frame(frame, terminal_size)
- else:
- cap = cv2.VideoCapture(args.video)
- assert cap.isOpened(), "Error opening video file"
- while cap.isOpened():
- ret, img = cap.read()
- if not ret:
- break
- img = cv2.resize(img, (img.shape[1], img.shape[0] // 2))
- if img.shape[1] > img.shape[0]:
- img = image_resize(img, height=terminal_size.lines - 2)
- else:
- img = image_resize(img, width=terminal_size.width)
- frame = frame_to_ascii_grayscale(img)
- render_frame(frame, terminal_size)
- cap.release()
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement