Python實現讓視訊自動打碼,再也不怕出現少兒不宜的畫面了

專注的阿熊發表於2022-04-16

import cv2

import face_recognition  # 人臉識別庫  99.7%    cmake  dlib  face_recognition

import subprocess

def video2mp3(file_name):

    outfile_name = file_name.split('.')[0] + '.mp3'

    cmd = 'ffmpeg -i ' + file_name + ' -f mp3 ' + outfile_name

    print(cmd)

    subprocess.call(cmd, shell=False)

def mask_video(input_video, output_video, mask_path='mask.jpg'):

    # 讀取圖片

    mask = cv2.imread(mask_path)

    # 讀取視訊

    cap = cv2.VideoCapture(input_video)

    # 視訊  fps  width  height

    v_fps = cap.get(5)

    v_width = cap.get(3)

    v_height = cap.get(4)

    # 設定寫入視訊引數  格式MP4

    # 畫面大小

    size = (int(v_width), int(v_height))

    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')

    # 輸出視訊

    out = cv2.VideoWriter(output_video, fourcc, v_fps, size)

    # 已知人臉

    known_image = face_recognition.load_image_file('tmr.jpg')

    biden_encoding = face_recognition.face_encodings(known_image)[0]

    cap = cv2.VideoCapture(input_video)

    while (cap.isOpened()):

        ret, frame = cap.read()

        if ret:

            # 檢測人臉

            # 人臉區域

            face_locations = face_recognition.face_locations(frame)

            for (top_right_y, top_right_x, left_bottom_y, left_bottom_x) in face_locations:

                print((top_right_y, top_right_x, left_bottom_y, left_bottom_x))

                unknown_image =外匯跟單gendan5.com frame[top_right_y - 50:left_bottom_y + 50, left_bottom_x - 50:top_right_x + 50]

                if face_recognition.face_encodings(unknown_image) != []:

                    unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

                    # 對比人臉

                    results = face_recognition.compare_faces([biden_encoding], unknown_encoding)

                    # [True]

                    # 貼圖

                    if results == [True]:

                        mask = cv2.resize(mask, (top_right_x - left_bottom_x, left_bottom_y - top_right_y))

                        frame[top_right_y:left_bottom_y, left_bottom_x:top_right_x] = mask

            out.write(frame)

        else:

            break

def video_add_mp3(file_name, mp3_file):

    outfile_name = file_name.split('.')[0] + '-f.mp4'

    subprocess.call('ffmpeg -i ' + file_name + ' -i ' + mp3_file + ' -strict -2 -f mp4 ' + outfile_name, shell=False)

if __name__ == '__main__':

    # 1.

    video2mp3('cut.mp4')

    # 2.

    mask_video(input_video='cut.mp4',output_video='output.mp4')

    # 3.

    video_add_mp3(file_name='output.mp4',mp3_file='cut.mp3')


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2887485/,如需轉載,請註明出處,否則將追究法律責任。

相關文章