我正在制作一个脚本,可以使用OpenCV和curses在命令行上播放视频。
from time import sleep
import curses
import numpy as np
import cv2 as cv
SOURCE_VIDEO = "foo.mp4"
DOWNSCALE_FACTOR = 8
def main(stdscr):
curses.curs_set(0)
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_WHITE)
cap = cv.VideoCapture(SOURCE_VIDEO)
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv.CAP_PROP_FPS)
while cap.isOpened():
# Read the next frame of the video.
_, frame = cap.read()
# Print the frame's ASCII approximation.
for y in range(0, height, DOWNSCALE_FACTOR):
for x in range(0, width, DOWNSCALE_FACTOR):
px = np.mean(frame[y][x:x+DOWNSCALE_FACTOR], axis=(0, 1)).round()
if px > 128:
stdscr.addstr("##", curses.color_pair(1))
else:
stdscr.addstr(" ")
stdscr.addstr("\n")
# Move the cursor back to the top left corner and refresh the screen.
stdscr.move(0, 0)
stdscr.refresh()
sleep(1 / fps) # I know this is a very imprecise method of timing the frames but it'll do for now.
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
curses.wrapper(main)
这在大多数情况下效果很好,但是,只要有运动,屏幕上的部分就会非常明显地闪烁。我该如何避免/减少这种情况?
如果这有任何区别,我将Windows Terminal与Ubuntu 20.04 WSL一起使用。