2

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

这是我的代码(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: cv2.VideoWriter_fourcc的反义词是什么?

4

1 回答 1

1

我改变了这一行:

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

至:

video_out = cv2.VideoWriter(
    "mtcnn.avi", cv2.VideoWriter_fourcc(*'XVID'), fps, (width, height))

现在它对我有用

于 2020-11-16T09:56:51.470 回答