The output video has only 1kB and can not be opened. What is wrong? This is my code:
import cv2
import numpy as np
file_name = "Touhou - Bad Apple.mp4"
output_file_name = "Touhou - Bad Apple difference flip.mp4"
# Open the video file
video = cv2.VideoCapture(file_name)
# Get the dimensions of the video
frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_rate = video.get(cv2.CAP_PROP_FPS)
# Create a VideoWriter object to write the new video file
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for .mp4 files
new_video = cv2.VideoWriter(output_file_name, fourcc, frame_rate, (frame_width, frame_height))
# Create first frame
new_frame = np.random.randint(0, 256, (frame_height, frame_width), dtype=np.uint8)
new_video.write(new_frame)
# Read and write the remaining frames
success, current_video_frame = video.read()
while True:
success, next_video_frame = video.read()
if not success:
break
difference = cv2.absdiff(current_video_frame, next_video_frame)
difference = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY)
new_frame = new_frame + difference
new_video.write(new_frame)
current_video_frame = next_video_frame
cv2.imshow('Difference', new_frame)
if cv2.waitKey(1) == ord('q'):
break
# Release the video objects
video.release()
new_video.release()
cv2.destroyAllWindows()
Random text so that stack overflow lets me post it. Random text so that stack overflow lets me post it. Random text so that stack overflow lets me post it. Random text so that stack overflow lets me post it. Random text so that stack overflow lets me post it. Random text so that stack overflow lets me post it. Random text so that stack overflow lets me post it.
The output video has only 1kB and can not be opened. What is wrong?
The problem can be fixed.
Modify the codec on line 17 from *mp4 to *'h264'.
Change this:
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for .mp4 files
to:
fourcc = cv2.VideoWriter_fourcc(*'h264') # Codec for .mp4 files
Output playback video: