I am trying to read a video, crop each frame from top and bottom and then write back each frame and also write them in to a video in mp4 format. The input video is at 2fps and it is also in mp4 format. The frames are saving properly but I can not write them as a 2fps video. I have tried other frame rates such as 1fps, 3fps, 5fps, 10fps and even 25fps. All of them work properly except 2fps, which result in a corrupted video (either its not showing any fame except the fist frame, or its just displaying a green screen) Any thoughts or comments will be appreciated:
reader = cv2.VideoCapture('video.mp4')
cropped_video = os.path.join('video_crop.mp4')
cropped_frames = os.path.join('video/')
if (reader.isOpened() == False):
print('Error while trying to open video. Plese check again...')
else:
# get the frame width and height
frame_width = int(reader.get(cv2.CAP_PROP_FRAME_WIDTH ))
frame_height = int(reader.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_count = int(reader.get(7))
fps = int(reader.get(cv2.CAP_PROP_FPS))
print('frame_width, frame_height, frame_count, fps = ', frame_width, frame_height, frame_count, fps)
# define codec and create VideoWriter object
fourcc= cv2.VideoWriter_fourcc(*'XVID')#*"MP4V")
writer = cv2.VideoWriter(cropped_video , fourcc, 2, (frame_width, frame_height))
top = 20
botton= frame_height-20
count = 0
# read until end of video
while True:
ret, frame = reader.read()
if ret==True:
cropped = frame[top:botton , :]
frame = cv2.resize(cropped, (frame_width, frame_height), interpolation = cv2.INTER_NEAREST_EXACT)
# save video frame
cv2.imwrite(os.path.join(cropped_frames,"frame%d.jpg" % count), frame)
writer.write(frame)
count += 1
print(count)
else:
break
# release VideoCapture()
reader.release()
writer.release()
# close all frames and video windows
cv2.destroyAllWindows()