最近很火的武汉樱花开放程序代码

特殊时期火爆公众号的python小程序,周末闲着无聊照写了一遍…
原作者:武汉大学朱永春同学

cv_2.py

import cv2

vidcap = cv2.VideoCapture('video/video.avi')
count = 0
while True:
    success, image = vidcap.read()
    if success:
        cv2.imwrite("pic/frame%d.jpg" % count,image) # save frame as JPEG file
        if cv2.waitKey(10) == 27:
            break
        count += 1

print('视频转图片处理完成!')

cv_3.py

from PIL import Image,ImageDraw,ImageFont
import cv2
import os


def draw(pic):
    img = cv2.imread('pic/' + pic)
    img = img[:,:,(2,1,0)]

    blank = Image.new("RGB", [len(img[0]),len(img)], "white")
    drawObj = ImageDraw.Draw(blank)

    n = 10

    font = ImageFont.truetype('C:/Windows/Fonts/Microsoft YaHei UI/msyhbd.ttc',size=n-1)
    for i in range(0, len(img),n):
        for j in range(0, len(img[i]), n):
            text = '武汉加油'
            drawObj.ink = img[i][j][0] + img[i][j][1]*256 + img[i][j][2]*256*256
            drawObj.text([j,i], text[int(j/n)%len(text)],font=font)
            print('完成处理----',i,j)

    blank.save('new/new_'+pic, 'jpeg')

filelist = os.listdir('pic')
for file in filelist:
    draw(file)

cv_4.py

import os
import cv2
import re

def resort(list):
    for i in range(len(list)-1):
        for j in range(len(list) - 1):
            if int(re.findall(r'\d+', list[j])[0]) > int(re.findall(r'\d+', list[j+1])[0]):
                list[j], list[j+1] = list[j+1], list[j]
    return list


def picvideo(path, size):
    '''

    :param path:图片所在文件夹
    :param size:图片分辨率
    :return:
    '''
    filelist = os.listdir(path)
    filelist = resort(filelist)


    '''
    fps:
    帧率:1秒钟有n张图片写进去[比如控制一张图片停留5秒钟,那帧率为1时需要重复播放这张图片5次]
    如果文件夹下有50张534*300的图片,这里设置1秒钟播放5张,那么这个视频的时长就是10秒
    '''
    fps = 24
    file_path = 'video/new.mp4'
    fourcc = cv2.VideoWriter_fourcc('D','I','V','X')  # 不同的视频编码对应不同的视频格式
    video = cv2.VideoWriter(file_path, fourcc, fps, size)

    for item in filelist:
        if item.endswith('.jpg'):
            item = path + '/' + item
            img = cv2.imread(item)  ## 使用opencv读取图片,直接返回numpy.ndarray对象,通道顺序为BGR,注意是BGR,通道默认值范围0-255
            video.write(img)  # 把图片写进视频
    video.release()   # 释放

picvideo(r'new',(960,544))

注意

(1)不要直接pip install cv2,而是pip install opencv-python 来安装cv2模块
(2)自行去网上下载原始樱花绽放video,比较大900多M
(3)有了这个demo以后就可以搞点小玩意玩玩

参考

1.公众号【Python开发者】(上热搜!武大学生用 Python 敲出樱花开放)
2.武大学生用python敲出樱花开放|附源码

你可能感兴趣的:(Python)