作者仅用了50行不到的代码,就实现了这个效果,真的很酷。
详细代码请自己到Github去看看
https://github.com/dafarry/white-cuts-across-black-background
#!/usr/bin/env python3import tkinter as tkimport numpy as npfrom PIL import Image, ImageDraw, ImageChops, ImageOps, ImageFilter, ImageEnhanceimport os, shutilsize=800blankimg = Image.new('L', (size, size), color=0)shutil.rmtree("vidcuts", ignore_errors=True)os.makedirs("vidcuts")img = blankimg.copy()cuts, reps = 20, 8for cut in range(cuts * reps): rand = np.random.RandomState(cut % cuts + 100) anglerotate = np.exp(rand.uniform(0, np.pi) * 2j) angleshift = np.array([anglerotate * 1j]).view(float) offset = rand.uniform(0.05, 0.4) randomwalk = np.cumsum(rand.uniform(-0.0015, 0.0015, 2*size)) smoothline = np.convolve(randomwalk,np.ones(10)/10,'same') centeredline = (smoothline - smoothline[len(smoothline) // 2]) offsetline = centeredline + offset complexline = offsetline * 1j + np.linspace(-1, 1, len(offsetline)) maskbox = [1 -2j, -1 -2j] rotatedline = np.hstack((maskbox, complexline)) * anglerotate linelist = list(((rotatedline.view(float) + 0.5) * size).astype(int)) imgline = blankimg.copy() ImageDraw.Draw(imgline).line(linelist, fill=255, width=2) mask1 = imgline.copy() ImageDraw.Draw(mask1).polygon(linelist, fill=255) mask2 = ImageChops.lighter(imgline, ImageChops.invert(mask1)) img = ImageChops.lighter(img, imgline) split1 = ImageChops.darker(img, mask1) split2 = ImageChops.darker(img, mask2) splitsize = rand.randint(10, 20) lineblur = imgline.filter(ImageFilter.GaussianBlur(radius=10)) for step in range(10): shift = 2 + splitsize * step / 10 splitstep = (angleshift * shift).astype(int) shifted1 = ImageChops.offset(split1, *-splitstep) shifted2 = ImageChops.offset(split2, *splitstep) img = ImageChops.lighter(shifted1, shifted2) flash = ImageEnhance.Contrast(lineblur).enhance(10 - 2 * step) flashimg = ImageChops.lighter(img, flash) cropimg = ImageOps.crop(flashimg, border=size*.05) cropimg.save('vidcuts/file{:04d}.png'.format(cut % cuts * 10 + step))os.system("ffmpeg -y -framerate 20 -i vidcuts/file%04d.png " + "-loglevel warning -pix_fmt yuv420p cuts-anim.mp4")
当然,也可以直接安装和使用
如何运行
我这样做是作为“快速”编码挑战,但是我必须承认,事实证明,它比我预期的要困难得多。我必须从“pillow”图像库中导入几乎所有各种图形模块,以获取足够的功能使其正常工作。不过,我认为这是花费相当多的时间,因为与以前相比,我现在对该图像库了解更多。
随机数生成器的播种方式使其每20个剪切重复一次。我对该序列进行了八次重复,仅保存了最后一个。前七个重复足以以第八次恰好重复的方式填充背景。
Python库的安装说明
视窗
从python.org下载并安装最新的Python
然后在Windows命令提示符下,按如下所示安装库:
python -m pip install --upgrade pippython -m pip install --upgrade wheel setuptoolspython -m pip install numpypython -m pip install pillow
从ffmpeg.org下载FFMpeg
在撰写本文时,使用了FFMpeg的4.2.1版本。
仅需要使用“ makevideo” python脚本制作mpeg视频。
解压缩文件,然后将ffmpeg.exe放在PATH的某个位置,例如:在C: WINDOWS中
Ubuntu和Debian
在撰写本文时,可与系统Python3版本3.8.2正常运行
使用sudo apt install安装以下软件包
python3-numpy python3-tk python3-pil python3-pil.imagetk ffmpeg
(与PyPI中的PIL不同,“ imagetk”被拆分为一个单独的程序包,这有点“陷阱”。)