OpenCV Python VideoWriter menyimpan video yang rusak

Sep 16 2020

Saya mencoba mendapatkan contoh yang sangat sederhana tentang menyalin video sebelum saya mulai memodifikasi bingkai dalam video. Namun, video output.avi adalah file rusak 5kb dibandingkan dengan video barriers.avi 2,8 mb. Saya menggunakan OpenCV versi 4.2.0 dan Python versi 3.7.7.

Ini kodenya:

import cv2

input = cv2.VideoCapture("../video/barriers.avi")
height = int(input.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(input.get(cv2.CAP_PROP_FRAME_WIDTH))

fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('../video/output5.avi', fourcc, 30, (height, width), isColor=True)

while input.isOpened():
    # get validity boolean and current frame
    ret, frame = input.read()

    # if valid tag is false, loop back to start
    if not ret:
        break
    else:
        out.write(frame)

input.release()
out.release()

Jika saya mencetak bentuk bingkai, saya mendapatkan:

(480, 640, 3)

Catatan: Tidak ada solusi stack overflow lain yang membantu.

Edit: Semua bingkai ditampilkan dengan baik jika cv2.imshow () digunakan.

Jawaban

3 Ahx Sep 16 2020 at 03:08

Saya ingin mengatasi dua masalah dalam kode Anda:


Masalah # 1:: Anda ingin membuat.avifile video. Oleh karena itu, Anda perlu menginisialisasi fourcc Anda sebagaiMJPG:

fourcc = cv2.VideoWriter_fourcc(*'MJPG')

Ada kombinasi tertentu untuk membuat file video. Misalnya, jika Anda ingin membuat, .mp4Anda menginisialisasi fourcc sebagai *'mp4v'.


Masalah # 2: Pastikan ukuran video keluaran sama dengan bingkai masukan. Misalnya: Anda menyatakan ukuran objek Videowriter Anda(height, width). Maka bingkai Anda harus berukuran sama:

frame = cv2.resize(frame, (height, width))

Kode:


import cv2

cap = cv2.VideoCapture("output.mp4")
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('output5.avi', fourcc, 30, (width, height), isColor=True)

while cap.isOpened():
    # get validity boolean and current frame
    ret, frame = cap.read()

    # if valid tag is false, loop back to start
    if not ret:
        break
    else:
        frame = cv2.resize(frame, (width, height))
        out.write(frame)

cap.release()
out.release()