🔥 作者:FrigidWinter
🔥 簡介:主攻機器人與人工智能領域的理論研究和工程應用,業余豐富各種技術堆疊,主要涉足:【機器人(ROS)】【機器學習】【深度學習】【計算機視覺】
🔥 專欄:
- 《機器人原理與技術》
- 《計算機視覺教程》
- 《機器學習》
- 《嵌入式系統》
- …
目錄
- 0 寫在前面
- 1 視頻幀采樣
- 2 將圖片轉為字符畫
- 2.1 創建像素-字符索引
- 2.2 將圖片逐像素轉換為字符
- 3 將字符影像合成視頻
- 4 完整代碼
- 5 參考
0 寫在前面
放鞭炮賀新春,在我國有兩千多年歷史,關于鞭炮的起源,有個有趣的傳說,
西方山中有焉,長尺余,一足,性不畏人,犯之令人寒熱,名曰年驚憚,后人遂象其形,以火藥為之,——《神異經》
當初人們燃竹而爆,是為了驅嚇危害人們的山魈,據說山魈最怕火光和響聲,所以每到除夕,人們便“燃竹而爆”,把山魈嚇跑,這樣年復一年,便形成了過年放鞭炮、點紅燭、敲鑼打鼓歡慶新春的年俗,
新年新氣象,今天就用代碼來制作一個 動態鞭炮 ,效果如下所示,

動態鞭炮的基本原理是:將一個錄制好的鞭炮視頻以字符畫的形式復現,基本步驟是幀采樣 → 逐幀轉換為字符畫 → 字符畫合成視頻,下面開始吧!
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()
5 參考
[1] B站《大二AE結課作業 《過 年》(已擺爛)》
[2] https://hongcyu.cn/posts/opencv-pictovideo.html
- 動態編織中國結

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417155.html
標籤:AI
上一篇:pandas 高級
