網站首頁 編程語言 正文
前言:
放鞭炮賀新春,在我國有兩千多年歷史。關于鞭炮的起源,有個有趣的傳說。
西方山中有焉,長尺余,一足,性不畏人。犯之令人寒熱,名曰年驚憚,后人遂象其形,以火藥為之。——《神異經》
當初人們燃竹而爆,是為了驅嚇危害人們的山魈。據說山魈最怕火光和響聲,所以每到除夕,人們便“燃竹而爆”,把山魈嚇跑。這樣年復一年,便形成了過年放鞭炮、點紅燭、敲鑼打鼓歡慶新春的年俗。
新年新氣象,今天就用代碼來制作一個 動態鞭炮 ,
效果如下所示:
動態鞭炮的基本原理是:將一個錄制好的鞭炮視頻以字符畫的形式復現,基本步驟是幀采樣 → 逐幀轉換為字符畫 → 字符畫合成視頻。下面開始吧!
1 視頻幀采樣
函數如下所示,主要功能是將視頻的圖像流逐幀保存到特定的緩存文件夾中(若該文件夾不存在會自動創建)。函數輸入vp是openCV
視頻句柄,輸出number
是轉換的圖片數。
def video2Pic(vp): ? ? number = 0 ? ? if vp.isOpened(): ? ? ? ? r,frame = vp.read() ? ? ? ? if not os.path.exists('cachePic'): ? ? ? ? ? ? os.mkdir('cachePic') ? ? ? ? os.chdir('cachePic') ? ? else: ? ? ? ? r = False ? ? while r: ? ? ? ? number += 1 ? ? ? ? cv2.imwrite(str(number)+'.jpg',frame) ? ? ? ? r,frame = vp.read() ? ? os.chdir("..") ? ? return number
2 將圖片轉為字符畫
2.1 創建像素-字符索引
函數輸入像素RGBA
值,輸出對應的字符碼。其原理是將字符均勻地分布在整個灰度范圍內,像素灰度值落在哪個區間就對應哪個字符碼。字符碼可以參考 ASCII碼
ASCII 碼使用指定的7 位或8 位二進制數組合來表示128 或256 種可能的字符。標準ASCII 碼也叫基礎ASCII碼,使用7 位二進制數(剩下的1位二進制為0)來表示所有的大寫和小寫字母,數字0 到9、標點符號,以及在美式英語中使用的特殊控制字符。其中:0~31及127(共33個)是控制字符或通信專用字符(其余為可顯示字符),如控制符:LF(換行)、CR(回車)、FF(換頁)、DEL(刪除)、BS(退格)、BEL(響鈴)等;通信專用字符:SOH(文頭)、EOT(文尾)、ACK(確認)等;ASCII值為8、9、10 和13 分別轉換為退格、制表、換行和回車字符。它們并沒有特定的圖形顯示,但會依不同的應用程序,而對文本顯示有不同的影響。
RGBA
是代表Red(紅色)、Green(綠色)、Blue(藍色)和Alpha的色彩空間,Alpha通道一般用作不透明度參數。如果一個像素的alpha通道數值為0%,那它就是完全透明的,而數值為100%則意味著一個完全不透明的像素(傳統的數字圖像)。gray=0.2126 * r + 0.7152 * g + 0.0722 * b是RGB轉為灰度值的經驗公式,人眼對綠色更敏感。
def color2Char(r,g,b,alpha = 256): ? ? imgChar= list("#RMNHQODBWGPZ*@$C&98?32I1>!:-;. ") ? ? if alpha: ? ? ? gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) ? ? ? unit = 256 / len(imgChar) ? ? ? return imgChar[int(gray / unit)] ? ? else: ? ? ? return ''
2.2 將圖片逐像素轉換為字符
核心代碼如下,遍歷圖片的每個像素
? ? img = Image.open(imagePath).convert('RGB').resize((imgWidth, imgHeight),Image.NEAREST) ? ? for i in range(imgHeight): ? ? ? ? for j in range(imgWidth): ? ? ? ? ? ? pixel = img.getpixel((j, i)) ? ? ? ? ? ? color.append((pixel[0],pixel[1],pixel[2])) ? ? ? ? ? ? txt = txt + color2Char(pixel[0], pixel[1], pixel[2], pixel[3]) if len(pixel) == 4 else \ ? ? ? ? ? ? ? ? ? txt + color2Char(pixel[0], pixel[1], pixel[2])? ? ? ? ? txt += '\n' ? ? ? ? color.append((255,255,255))
3 將字符圖像合成視頻
輸入參數vp是openCV
視頻句柄,number
是幀數,savePath是視頻保存路徑,函數中 MP42 是可以生成較小并且較小的視頻文件的編碼方式,其他類似的還有isom、mp41、avc1、qt等,表示“最好”基于哪種格式來解析當前的文件。
def img2Video(vp, number, savePath): ? ? videoFourcc = VideoWriter_fourcc(*"MP42") ?# 設置視頻編碼器 ? ? asciiImgPathList = ['cacheChar' + r'/{}.jpg'.format(i) for i in range(1, number + 1)] ? ? asciiImgTemp = Image.open(asciiImgPathList[1]).size ? ? videoWritter= VideoWriter(savePath, videoFourcc, vp.get(cv2.CAP_PROP_FPS), asciiImgTemp) ? ? for imagePath in asciiImgPathList: ? ? ? ? videoWritter.write(cv2.imread(imagePath)) ? ? videoWritter.release()
4 完整代碼
import cv2? from PIL import Image,ImageFont,ImageDraw import os from cv2 import VideoWriter, VideoWriter_fourcc ''' * @breif: 將像素顏色轉換為ASCII字符 * @param[in]: 像素RGBA值 * @retval: 字符 ''' def color2Char(r,g,b,alpha = 256): ? ? imgChar = list("#RMNHQODBWGPZ*@$C&98?32I1>!:-;. ") ? ? if alpha: ? ? ? gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) ? ? ? unit = 256 / len(imgChar) ? ? ? return imgChar[int(gray / unit)] ? ? else: ? ? ? return '' ? ''' * @breif: 將視頻逐幀轉換為圖片 * @param[in]: vp -> openCV視頻句柄 * @retval: number -> 轉換的圖片數 ''' def video2Pic(vp): ? ? number = 0 ? ? if vp.isOpened(): ? ? ? ? r,frame = vp.read() ? ? ? ? if not os.path.exists('cachePic'): ? ? ? ? ? ? os.mkdir('cachePic') ? ? ? ? os.chdir('cachePic') ? ? else: ? ? ? ? r = False ? ? while r: ? ? ? ? number += 1 ? ? ? ? cv2.imwrite(str(number)+'.jpg',frame) ? ? ? ? r,frame = vp.read() ? ? os.chdir("..") ? ? return number ? ''' * @breif: 將圖片逐像素轉換為ASCII字符 * @param[in]: imagePath -> 圖片路徑 * @param[in]: index -> 圖片索引 * @retval: None ''' def img2Char(imagePath, index): ? ? # 初始化 ? ? txt, color, font = '', [], ImageFont.load_default().font ? ? imgWidth, imgHeight = Image.open(imagePath).size ? ? asciiImg = Image.new("RGB",(imgWidth, imgHeight), (255,255,255)) ? ? drawPtr = ImageDraw.Draw(asciiImg) ? ? imgWidth, imgHeight = int(imgWidth / 6), int(imgHeight / 15) ? ? # 對圖像幀逐像素轉化為ASCII字符并記錄RGB值 ? ? img = Image.open(imagePath).convert('RGB').resize((imgWidth, imgHeight),Image.NEAREST) ? ? for i in range(imgHeight): ? ? ? ? for j in range(imgWidth): ? ? ? ? ? ? pixel = img.getpixel((j, i)) ? ? ? ? ? ? color.append((pixel[0],pixel[1],pixel[2])) ? ? ? ? ? ? txt = txt + color2Char(pixel[0], pixel[1], pixel[2], pixel[3]) if len(pixel) == 4 else \ ? ? ? ? ? ? ? ? ? txt + color2Char(pixel[0], pixel[1], pixel[2])? ? ? ? ? txt += '\n' ? ? ? ? color.append((255,255,255)) ? ?? ? ? # 繪制ASCII字符畫并保存 ? ? x, y = 0,0 ? ? fontW, fontH = font.getsize(txt[1]) ? ? fontH *= 1.37 ? ? for i in range(len(txt)): ? ? ? ? if(txt[i]=='\n'): ? ? ? ? ? ? x += fontH ? ? ? ? ? ? y = -fontW ? ? ? ? drawPtr.text((y,x), txt[i], fill=color[i]) ? ? ? ? y += fontW ? ? os.chdir('cacheChar') ? ? asciiImg.save(str(index)+'.jpg') ? ? os.chdir("..") ''' * @breif: 將視頻轉換為ASCII圖像集 * @param[in]: number -> 幀數 * @retval: None '''? def video2Char(number): ? ? if not os.path.exists('cacheChar'): ? ? ? ? os.mkdir('cacheChar') ? ? img_path_list = ['cachePic' + r'/{}.jpg'.format(i) for i in range(1, number + 1)]? ? ? task = 0 ? ? for imagePath in img_path_list: ? ? ? ? task += 1 ? ? ? ? img2Char(imagePath, task) ''' * @breif: 將圖像合成視頻 * @param[in]: vp -> openCV視頻句柄 * @param[in]: number -> 幀數 * @param[in]: savePath -> 視頻保存路徑 * @retval: None ''' ? def img2Video(vp, number, savePath): ? ? videoFourcc = VideoWriter_fourcc(*"MP42") ?# 設置視頻編碼器 ? ? asciiImgPathList = ['cacheChar' + r'/{}.jpg'.format(i) for i in range(1, number + 1)] ? ? asciiImgTemp = Image.open(asciiImgPathList[1]).size ? ? videoWritter= VideoWriter(savePath, videoFourcc, vp.get(cv2.CAP_PROP_FPS), asciiImgTemp) ? ? for imagePath in asciiImgPathList: ? ? ? ? videoWritter.write(cv2.imread(imagePath)) ? ? videoWritter.release() ? ?? if __name__ == '__main__':? ? videoPath = 'test.mp4' ? savePath = 'new.avi' ? vp = cv2.VideoCapture(videoPath) ? number = video2Pic(vp) ? video2Char(number) ? img2Video(vp, number, savePath) ? vp.release()
到此這篇關于 Python 代碼制作動態鞭炮的文章就介紹到這了,更多相關 Python 制作動態鞭炮內容請搜索AB教程網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持AB教程網!
5 參考
原文鏈接:https://blog.csdn.net/FRIGIDWINTER/article/details/122601693
相關推薦
- 2022-12-04 Android嵌套線性布局玩法坑解決方法_Android
- 2022-11-02 Python+requests+unittest執行接口自動化測試詳情_python
- 2022-06-14 Flutter?RSA加密解密的示例代碼_Android
- 2024-02-29 UNI-APP項目在引用官方提供的Uni-App-Demo實例中的組件時應該注意的問題
- 2023-01-31 基于C#實現獲取本地磁盤目錄_C#教程
- 2022-11-27 搭建?Selenium+Python開發環境詳細步驟_python
- 2022-06-09 教你在k8s上部署HADOOP-3.2.2(HDFS)的方法_云其它
- 2022-11-19 詳解C語言內核中的自旋鎖結構_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支