python里的resize_Python玩转蔡徐坤
生活随笔
收集整理的這篇文章主要介紹了
python里的resize_Python玩转蔡徐坤
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
很無聊地做了一個視頻轉字符圖的Python代碼,把最近火的一趟糊涂的蔡徐坤轉成字符圖像。
效果可以看這里
https://www.bilibili.com/video/av50295619/?www.bilibili.com思路很簡單,借助OpenCV讀取視頻提取圖像,圖像轉灰度圖,再量化,根據量化值取字符。
代碼及注釋如下:
import cv2 import time import numpy as np import curses# pixel后面4位都是空格,代表像素值比較大的 # 近似白色背景 pixels = " .,-'`:!1+*% "def get_images(video_name, size):'''視頻幀分解圖像轉灰度圖,再縮放:param video_name::param size::return: 灰度圖列表'''img_list = []cap = cv2.VideoCapture(video_name)while cap.isOpened():ret, frame = cap.read()if ret:gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)img = cv2.resize(gray, size, interpolation=cv2.INTER_AREA)img_list.append(img)else:breakcap.release()return img_listdef img_2_char(img):'''灰度圖像映射成字符[0,255] -> [0,16]用[0,16]索引值取字符:param img::return: 字符數組'''ret = []p = img / 255indexes = (p * (len(pixels) - 1)).astype(np.int)height, width = img.shapefor row in range(height):line = ""for col in range(width):index = indexes[row][col]line += pixels[index] + " "ret.append(line)return retdef video_2_char(img_list):'''圖像列表 轉換成 字符圖列表:param img_list::return:'''video_char = []for img in img_list:pic = img_2_char(img)video_char.append(pic)return video_chardef play_video(video_char):width, height = len(video_char[0][0]), len(video_char[0])stdscr = curses.initscr()curses.start_color()try:stdscr.resize(height, width * 2)for pic_i in range(len(video_char)):for line_i in range(height):# 將pic_i的第i行寫入第i列。(line_i, 0)表示從第i行的開頭開始寫入。最后一個參數設置字符為白色stdscr.addstr(line_i, 0, video_char[pic_i][line_i], curses.COLOR_WHITE)stdscr.refresh() # 寫入后需要refresh才會立即更新界面time.sleep(1 / 24)finally:curses.endwin()if __name__ == "__main__":imgs = get_images('c:videokun.mp4', (64, 40))video_chars = video_2_char(imgs)play_video(video_chars)注意事項:
進入命令行控制臺,使用pip install opencv-python 安裝cv2
http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses
下載curses, 然后用 pip install 文件名.whl 安裝curses
pip install numpy 安裝numpy
最后,運行程序時,務必在命令行里敲入: python 腳本名.py
厚臉皮 一波
凱威講堂?www.kaiweitalk.com總結
以上是生活随笔為你收集整理的python里的resize_Python玩转蔡徐坤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: qpython3l手机版怎么用_qpyt
- 下一篇: oracle schema_Oracle