如何使用cv2和MTCNN在视频上书写?我遇到了Fourcc的问题

问题描述

我正在尝试编写一个使视频中的面孔匿名化的脚本。

这是我的代码(python):

import cv2
from mtcnn.mtcnn import MTCNN

ksize = (101,101)


def decode_fourcc(cc):
    return "".join([chr((int(cc) >> 8 * i) & 0xFF) for i in range(4)])


def find_face_MTCNN(color,result_list):
    for result in result_list:
        x,y,w,h = result['Box']
        roi = color[y:y+h,x:x+w]
        cv2.rectangle(color,(x,y),(x+w,y+h),(0,155,255),5)
        detectedFace = cv2.GaussianBlur(roi,ksize,0)
        color[y:y+h,x:x+w] = detectedFace
    return color


detector = MTCNN()
video_capture = cv2.VideoCapture("basic.mp4")
width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
fps = int(video_capture.get(cv2.CAP_PROP_FPS))

video_out = cv2.VideoWriter(
    "mtcnn.mp4",cv2.VideoWriter_fourcc(*"mp4v"),fps,(width,height))

while length:
    _,color = video_capture.read()
    faces = detector.detect_faces(color)
    detectFaceMTCNN = find_face_MTCNN(color,faces)
    video_out.write(detectFaceMTCNN)
    cv2.imshow("Video",detectFaceMTCNN)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

fourccIN = video_capture.get(cv2.CAP_PROP_FOURCC)
fourccOUT = video_out.get(cv2.CAP_PROP_FOURCC)
print(f"input fourcc is: {fourccIN,decode_fourcc(fourccIN)}")
print(f"output fourcc is: {fourccOUT,decode_fourcc(fourccOUT)}")

video_capture.release()
cv2.destroyAllWindows()

通过匿名化,我将获得一个完美的工作窗口,因此imshow()可以正常工作。但是新保存的视频“ mtcnn.mp4”无法打开。我发现问题是新视频的fourcc格式,因为我的输出是:

input fourcc is: (828601953.0,'avc1')
output fourcc is: (-1.0,'ÿÿÿÿ')

'ÿÿÿÿ'代表不可读,因此这就是问题的核心...

有人可以帮我吗?

他们可能面临着同样的问题: Using MTCNN with a webcam via OpenCV

我用它来编码fourcc: What is the opposite of cv2.VideoWriter_fourcc?

解决方法

我更改了这一行:

NaN

收件人:

video_out = cv2.VideoWriter(
    "mtcnn.mp4",cv2.VideoWriter_fourcc(*"mp4v"),fps,(width,height))

现在它对我有用