首先导入需要的模块

import cv2
from numba import jit
import time

cv2是openCV模块,numba用于加快矩阵运算(对视频每帧的图像操作时要用到),time模块用于计时

读取视频,创建视频

video1=cv2.VideoCapture("video.mp4")
# 读取源视频
fps=video1.get(cv2.CAP_PROP_FPS)
# 获取源视频帧率
size=(int(video1.get(cv2.CAP_PROP_FRAME_WIDTH)),int(video1.get(cv2.CAP_PROP_FRAME_HEIGHT)))
# 获取源视频大小
fourcc=cv2.VideoWriter_fourcc('X','V','I','D')
# 生成视频的编码方式
video2=cv2.VideoWriter("videoOut2.avi",fourcc,fps,size)
# 生成视频

一些链接:

视频读写:https://blog.csdn.net/Arthur_Holmes/article/details/89847613?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

numba模块:https://www.cnblogs.com/yanxingang/p/10910090.html

将图片转为像素风格

@jit
def imgToMosaic(img,mosaicSize):
    h, w, ch = img.shape
    for m in range(h):
        for n in range(w):
            if m % mosaicSize == 0 and n % mosaicSize == 0:
                for i in range(mosaicSize):
                    for j in range(mosaicSize):
                        (b, g, r) = img[m, n]
                        if i+m<h and j+n<w:
                            img[i + m, j + n] = (b, g, r)
    return img

像素风图片算法:https://blog.csdn.net/missyougoon/article/details/81142915?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

将视频转为像素风格

def videoToMosaic(videoIn,videoOut,mosaicSize):
    time1 = time.time()
    pos = 0
    while True:
        pos += 1
        ret, frame = video1.read()
        if ret:
            print("第", pos, "帧")
            videoOut.write(imgToMosaic(frame, mosaicSize))
        else:
            break
    time2 = time.time()
    print("共计耗时", time2 - time1, "s")
    videoIn.release()
    videoOut.release()

videoToMosaic(video1,video2,10)
# 改变数字大小获得不同效果

全部代码

import cv2
from numba import jit
import time

video1=cv2.VideoCapture("video.mp4")

fps=video1.get(cv2.CAP_PROP_FPS)
size=(int(video1.get(cv2.CAP_PROP_FRAME_WIDTH)),int(video1.get(cv2.CAP_PROP_FRAME_HEIGHT)))

fourcc=cv2.VideoWriter_fourcc('X','V','I','D')
video2=cv2.VideoWriter("videoOut.avi",fourcc,fps,size)

@jit
def imgToMosaic(img,mosaicSize):
    h, w, ch = img.shape
    for m in range(h):
        for n in range(w):
            if m % mosaicSize == 0 and n % mosaicSize == 0:
                for i in range(mosaicSize):
                    for j in range(mosaicSize):
                        (b, g, r) = img[m, n]
                        if i+m<h and j+n<w:
                            img[i + m, j + n] = (b, g, r)
    return img

def videoToMosaic(videoIn,videoOut,mosaicSize):
    time1 = time.time()
    pos = 0
    while True:
        pos += 1
        ret, frame = video1.read()
        if ret:
            print("第", pos, "帧")
            videoOut.write(imgToMosaic(frame, mosaicSize))
        else:
            break
    time2 = time.time()
    print("共计耗时", time2 - time1, "s")
    videoIn.release()
    videoOut.release()

videoToMosaic(video1,video2,10)

转换前后文件数据对比

转换消耗时间

效果

Last modification:July 12th, 2020 at 01:07 am