opencv给视频打马赛克

本文转至:opencv马赛克python实现

代码:

import cv2
import time
cap = cv2.VideoCapture("test.mp4")
path = "test_mosaic.mp4"

fourcc = cv2.VideoWriter_fourcc('M','P','4','V')  
fps = cap.get(cv2.CAP_PROP_FPS)
out = cv2.VideoWriter(path, fourcc, fps,(int(cap.get(3)), int(cap.get(4))), True)
#print('fps: ', fps)
#print(int(cap.get(3)), int(cap.get(4)))

def do_mosaic(frame, x, y, w, h, neighbor=5):
    """
    马赛克的实现原理是把图像上某个像素点一定范围邻域内的所有点用邻域内左上像素点的颜色代替,这样可以模糊细节,但是可以保留大体的轮廓。
    :param frame: opencv frame
    :param int x :  打码区域左顶点x
    :param int y:  打码区域左顶点y
    :param int w:  打码区域宽
    :param int h:  打码区域高
    :param int neighbor:  马赛克每一块的宽
    """
    fh, fw = frame.shape[0], frame.shape[1]
    if (y + h > fh) or (x + w > fw):
        print("超出视频尺寸!")
        return
    for i in range(0, h - neighbor, neighbor):
        for j in range(0, w - neighbor, neighbor):
            rect = [j + x, i + y, neighbor, neighbor]
            # color=frame[262][967].tolist()
            color = frame[i + y][j + x].tolist()
            left_up = (rect[0], rect[1])
            right_down = (rect[0] + neighbor - 1, rect[1] + neighbor - 1)  # 关键点2 减去一个像素
            cv2.rectangle(frame, left_up, right_down, color, -1)

ret, frame = cap.read()

while cap.isOpened():
    ret, frame = cap.read()

    if ret:
        time_sleep=1/fps
        do_mosaic(frame,965,255,149,244)# 打马部分左上角XY,打马区域wh
        cv2.imshow("frame", frame)
        # time.sleep(time_sleep) #按正常速播放
        out.write(frame)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()

对于需要打马位置坐标的确定,可以使用:ROI坐标点提取(python)

打马效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48994268/article/details/120512803