OpenCV Python VideoWriter บันทึกวิดีโอที่เสียหาย
ฉันพยายามหาตัวอย่างง่ายๆในการคัดลอกวิดีโอก่อนที่จะเริ่มแก้ไขเฟรมในวิดีโอ อย่างไรก็ตามวิดีโอ output.avi เป็นไฟล์ที่เสียหาย 5kb เมื่อเทียบกับวิดีโอ barriers.avi 2.8 mb ฉันใช้ OpenCV เวอร์ชัน 4.2.0 และ Python เวอร์ชัน 3.7.7
นี่คือรหัส:
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()
ถ้าฉันพิมพ์รูปร่างของเฟรมฉันจะได้รับ:
(480, 640, 3)
หมายเหตุ: ไม่มีวิธีแก้ปัญหาสแตกล้นอื่น ๆ ที่ช่วยได้
แก้ไข: เฟรมทั้งหมดจะแสดงผลได้ดีหากใช้ cv2.imshow ()
คำตอบ
ฉันต้องการแก้ไขปัญหาสองประการในรหัสของคุณ:
ปัญหา # 1:คุณต้องการสร้าง.aviไฟล์วิดีโอ ดังนั้นคุณต้องเริ่มต้น fourcc ของคุณเป็นMJPG:
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
มีชุดค่าผสมบางอย่างสำหรับการสร้างไฟล์วิดีโอ ตัวอย่างเช่นหากคุณต้องการสร้าง.mp4คุณเริ่มต้น fourcc ของคุณเป็น*'mp4v'.
ปัญหา # 2:ตรวจสอบให้แน่ใจว่าขนาดของวิดีโอเอาต์พุตตรงกับเฟรมอินพุต (height, width)ตัวอย่างเช่นคุณประกาศขนาดของวัตถุ Videowriter ของคุณ จากนั้นเฟรมของคุณจะต้องมีขนาดเท่ากัน:
frame = cv2.resize(frame, (height, width))
รหัส:
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()