新年新气象,100 行 Python 代码制作动态鞭炮

作者 | FrigidWinter
来源 | CSDN博客
放鞭炮贺新春,在我国有两千多年历史。关于鞭炮的起源,有个有趣的传说。
西方山中有焉,长尺余,一足,性不畏人。犯之令人寒热,名曰年惊惮,后人遂象其形,以火药为之。——《神异经》


def video2Pic(vp):number = 0if vp.isOpened():r,frame = vp.read()if not os.path.exists('cachePic'):os.mkdir('cachePic')os.chdir('cachePic')else:r = Falsewhile r:number += 1cv2.imwrite(str(number)+'.jpg',frame)r,frame = vp.read()os.chdir("..")return number
将图片转为字符画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))

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]).sizevideoWritter= VideoWriter(savePath, videoFourcc, vp.get(cv2.CAP_PROP_FPS), asciiImgTemp)for imagePath in asciiImgPathList:videoWritter.write(cv2.imread(imagePath))videoWritter.release()

import cv2from PIL import Image,ImageFont,ImageDrawimport osfrom 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 = 0if vp.isOpened():r,frame = vp.read()if not os.path.exists('cachePic'):os.mkdir('cachePic')os.chdir('cachePic')else:r = Falsewhile r:number += 1cv2.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().fontimgWidth, imgHeight = Image.open(imagePath).sizeasciiImg = 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,0fontW, fontH = font.getsize(txt[1])fontH *= 1.37for i in range(len(txt)):if(txt[i]=='\n'):x += fontHy = -fontWdrawPtr.text((y,x), txt[i], fill=color[i])y += fontWos.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 = 0for imagePath in img_path_list:task += 1img2Char(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]).sizevideoWritter= 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()


分享

点收藏

点点赞

点在看
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 习近平同马克龙交流互动的经典瞬间 7904310
- 2 黑龙江水库冰面下现13匹冰冻马 7808656
- 3 微信表情包戒烟再度翻红 7714374
- 4 2025你的消费习惯“更新”了吗 7618347
- 5 存100万存20万利率一样透露啥信号 7521065
- 6 劲酒如何成了年轻女性的神仙水 7425115
- 7 中俄两军举行第3次反导联合演习 7330896
- 8 女子裤子内藏2斤多活虫入境被查 7236018
- 9 杭州野生动物园黑熊突然袭击饲养员 7135480
- 10 中疾控流感防治七问七答 7046812







AI100
