python 给视频添加马赛克

Posted 牛郎

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 给视频添加马赛克相关的知识,希望对你有一定的参考价值。

用法:

1. 创建空文件夹:imgs

2. 将倒数第三行中的"222056.mov"改为你的视频路径,如:"a.mov"

3. 运行以下代码

4. 稍等片刻,鼠标拖动选择添加马赛克区域,按enter确定(每次操作只能添加一个马赛克区域,视频会根据所选区域全程添加马赛克)

5. 稍等片刻,‘a.avi ‘就是做好的视频文件,!!!注意!!!该视频文件没有音频

 

源码:

import cv2, os
import numpy as np

def video2img(videoroot):
    cap = cv2.VideoCapture(videoroot)
    isOpened = cap.isOpened    # 判断是否打开‘
    print(isOpened)
    fps = cap.get(cv2.CAP_PROP_FPS)    #帧率
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    print(fps,width,height)
    i = 0
    while(isOpened):
        i += 1
        (flag,frame) = cap.read() # 读取每一张 flag frame 
        fileName = ‘./imgs/image‘+str(i)+‘.jpg‘
        print(fileName)
        if flag == True:
            frame = np.rot90(frame, 1)
            cv2.imwrite(fileName,frame)
        else:
            break
    return fps

def img2video(outvideoroot, fps):
    img = cv2.imread(‘./imgs/image1.jpg‘)
    imgInfo = img.shape
    size = (imgInfo[1],imgInfo[0])
    print(size)
    fourcc = cv2.VideoWriter_fourcc(*‘XVID‘)
    videowriter = cv2.VideoWriter(outvideoroot,fourcc,fps,size)
    list_imgs = os.listdir(‘./imgs‘)
    for i in range(1, len(list_imgs)):
        fileName = ‘./imgs/image‘+str(i)+‘.jpg‘
        img = cv2.imread(fileName)
        videowriter.write(img)

def get_xoy():
    imgsroot = ‘./imgs‘
    list_ = os.listdir(imgsroot)
    for n in list_:
        path_ = os.path.join(imgsroot, n)
        img = cv2.imread(path_)
        bbox = cv2.selectROI(‘selectroi‘, img)
        break
    return bbox

def fitsign():
    box = get_xoy()
    xo, yo, w, h = box[0], box[1],box[2],box[3],
    print(box)
    dstroot = ‘./imgs‘
    dstlist = os.listdir(dstroot)
    kernel_size = (41, 41)
    sigma = 50
    for n in dstlist:
        path_ = os.path.join(dstroot, n)
        img = cv2.imread(path_)
        crop = img[yo:yo+h, xo:xo+w, :]
        crop = cv2.GaussianBlur(crop, kernel_size, sigma)
       # crop = cv2.blur(crop, (41,41))
        img[yo:yo+h, xo:xo+w, :] = crop
        cv2.imwrite(path_, img)

if __name__ == "__main__":
    fps = video2img("222056.mov")
    fitsign()
    img2video(‘a.avi‘, fps)

  

  

以上是关于python 给视频添加马赛克的主要内容,如果未能解决你的问题,请参考以下文章

绘声绘影给视频加多个马赛克和动态马赛克方法

实战|惊呆了,Python竟然能剪辑视频!

实战|惊呆了,Python竟然能剪辑视频!

python实战项目惊呆了,竟然能剪辑视频!

Python实现让视频自动打码,再也不怕出现少儿不宜的画面了

Python计算机视觉:视频人脸马赛克