How to blur particular element in the video mp4?

97 Views Asked by At

In my video, there is an element that needs to be blurred as much as possible. I have a photo of this element called photo.jpg. I need to correct my Python code that will fully blur this element in the video (taking into account that when the camera moves, the element will also be gradually disappearing from view) and save the video without any loss of audio. am trying to blur it in a video, but the new generated video doesn't have anything blurred...for some reasons...it simply doesnt work...Maybe some parameters need to be tuned..?

import cv2
import numpy as np
from moviepy.editor import *

def blur_element(video_path, image_path, output_path):
    # Загрузка видео
    video = VideoFileClip(video_path)

    # Загрузка изображения элемента и определение его размеров
    element_image = cv2.imread(image_path, cv2.IMREAD_COLOR)

    # Check if the image was loaded successfully
    if element_image is None:
        print("Error: Could not load the image.")
        return

    h, w, _ = element_image.shape

    # Определение функции для заблюривания элемента
    def blur_frame(t):
        # Получение кадра на момент времени t
        frame = video.get_frame(t)

        # Нахождение элемента на кадре
        result = cv2.matchTemplate(frame, element_image, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

        # Заблюривание элемента на кадре
        if max_val > 0.5:  # Порог подбирается экспериментально
            blurred_frame = cv2.GaussianBlur(frame, (99, 99), 30)  # Размытие элемента
        else:
            blurred_frame = frame

        return blurred_frame

    # Применение функции blur_frame к каждому кадру видео
    blurred_video = VideoClip(make_frame=blur_frame, duration=video.duration)
    blurred_video.fps = video.fps  # Set the fps for the output video

    # Сохранение видео без потери музыки
    final_video = blurred_video.set_audio(video.audio)
    final_video.write_videofile(output_path, codec="libx264", audio_codec="aac")

# Пример использования функции
video_path = "test.mp4"  # Путь к исходному видео
image_path = "photo.jpg"  # Путь к изображению элемента
output_path = "output.mp4"  # Путь к сохраняемому видео

blur_element(video_path, image_path, output_path)```
0

There are 0 best solutions below