How to write on video with cv2 AND MTCNN? I'm facing problems with fourcc

*爱你&永不变心* 提交于 2020-12-12 04:47:21

问题


I'm trying to write a script that anonymized faces on videos.

here is my code (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()

I'll get a perfect working window with the anonymization, so imshow() works fine. But the new saved video "mtcnn.mp4" can't be opened. I found out the problem is the fourcc format of the new video since my output is:

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

'ÿÿÿÿ' stands for unreadable so thats the core of the matter...

Can someone help me please?

They are facing probably the same problem: Using MTCNN with a webcam via OpenCV

And I used this to encode the fourcc: What is the opposite of cv2.VideoWriter_fourcc?


回答1:


I've changes this line:

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

to:

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

And now it works for me



来源:https://stackoverflow.com/questions/64803078/how-to-write-on-video-with-cv2-and-mtcnn-im-facing-problems-with-fourcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!