分享好友 编程语言首页 频道列表

Python绘制1000响大地红鞭炮动态效果

Python  2023-02-09 03:380

新年新气象,今天就用代码来制作一个 动态鞭炮 ,效果如下所示。

Python绘制1000响大地红鞭炮动态效果

动态鞭炮的基本原理是:将一个录制好的鞭炮视频以字符画的形式复现,基本步骤是帧采样 → 逐帧转换为字符画 → 字符画合成视频。下面开始吧!略略略~~~(本作品没有声音,想要声音的自己的嘴巴自己发声······你懂得

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、将字符图像合成视频

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()

好啦,这就是今天的内容,如果你那里还不能放鞭炮,那就来试试这个吧!!!!

原文地址:https://blog.csdn.net/m0_64122244/article/details/128496218

查看更多关于【Python】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
如何在Abaqus的python中调用Matlab程序
目录1. 确定版本信息2. 备份python3. 设置环境变量4. 安装程序5. 调试运行参考资料Abaqus2018操作系统Win10 64位Python版本2.7(路径C:\SIMULIA\CAE\2018\win_b64\tools\SMApy\python2.7)2. 备份python将上述的“python2.7”文件夹复制出来,避免因操作错误

0评论2023-03-16608

sf02_选择排序算法Java Python rust 实现
Java 实现package common;public class SimpleArithmetic {/** * 选择排序 * 输入整形数组:a[n] 【4、5、3、7】 * 1. 取数组编号为i(i属于[0 , n-2])的数组值 a[i],即第一重循环 * 2. 假定a[i]为数组a[k](k属于[i,n-1])中的最小值a[min],即执行初始化 min =i

0评论2023-02-09407

Python vs Ruby: 谁是最好的 web 开发语言?
Python 和 Ruby 都是目前用来开发 websites、web-based apps 和 web services 的流行编程语言之一。 这两种语言在许多方面有相似之处。它们都是高级的面向对象的编程语言,都是交互式脚本语言、都提供标准库且支持持久化。但是,Python 和 Ruby 的解决方法却

0评论2023-02-09819

Python+Sklearn实现异常检测
目录离群检测 与 新奇检测Sklearn 中支持的方法孤立森林 IsolationForestLocal Outlier FactorOneClassSVMElliptic Envelope离群检测 与 新奇检测很多应用场景都需要能够确定样本是否属于与现有的分布,或者应该被视为不同的分布。离群检测(Outlier detectio

0评论2023-02-09736

Python异常与错误处理详细讲解 python的异常
基础知识优先使用异常捕获LBYL(look before you leap): 在执行一个可能出错的操作时,先做一些关键的条件判断,仅当满足条件时才进行操作。EAFP(eaiser to ask for forgiveness than permission): 不做事前检查,直接执行操作。后者更优: 代码简洁,效率更高

0评论2023-02-09962

Python多线程与同步机制浅析
目录线程实现Thread类函数方式继承方式同步机制同步锁Lock条件变量Condition信号量Semaphore事件Event屏障BarrierGIL全局解释器锁线程实现Python中线程有两种方式:函数或者用类来包装线程对象。threading模块中包含了丰富的多线程支持功能:threading.curren

0评论2023-02-09409

python基础之reverse和reversed函数的介绍及使用
目录一、reverse二、reversed附:Python中reverse和reversed反转列表的操作方法总结一、reversereverse()是python中列表的一个内置方法(在字典、字符串和元组中没有这个内置方法),用于列表中数据的反转例子:lista = [1, 2, 3, 4]lista.reverse()print(lista

0评论2023-02-09878

Python多进程并发与同步机制超详细讲解
目录多进程僵尸进程Process类函数方式继承方式同步机制状态管理Managers在《多线程与同步》中介绍了多线程及存在的问题,而通过使用多进程而非线程可有效地绕过全局解释器锁。 因此,通过multiprocessing模块可充分地利用多核CPU的资源。多进程多进程是通过mu

0评论2023-02-09469

Python进程间通讯与进程池超详细讲解 python进程池的作用
目录进程间通讯队列Queue管道Pipe进程池Pool在《多进程并发与同步》中介绍了进程创建与信息共享,除此之外python还提供了更方便的进程间通讯方式。进程间通讯multiprocessing中提供了Pipe(一对一)和Queue(多对多)用于进程间通讯。队列Queue队列是一个可用

0评论2023-02-09797

Python PyMuPDF实现PDF与图片和PPT相互转换
目录安装与简介MuPDFPyMuPDFPyMuPDF使用元数据页面Page代码示例PDF转图片图片转PDFPDF转PPT文章目录 安装与简介MuPDFPyMuPDF PyMuPDF使用元数据页面Page 代码示例PDF转图片图片转PDFPDF转PPTPyMuPDF提供了PDF及流行图片处理接口。安装与简介安装:pip install

0评论2023-02-09349

更多推荐