Help rotating a mp4 video clip which was rotated in the middle of the video

I have a mp4 video that was originally shot with an iPhone. The user rotated the phone while recording the video, so 1/4 is in portrait mode and 3/4 is in landscape mode.

Is there a way using Python and OpenCV to correct the rotation of the video so the entire video is in one mode - either portrait or landscape?

I could use a “standard” video editor like Openshot to cut the video into 3 pieces, (1) the portrait mode part, (2) the intermediate rotation frames, and (3) the landscape part, discard the second part, rotate the third part, and then join the rotated third part with the first part. But the result is terrible due to the missing frames.

is there a better way to do it frame by frame in Python using OpenCV?


this is a one-time task.

do not seek ways to “program” this.

get a video editor program.

split where the camera is turned. apply rotation to the segment that needs it. done. or apply the rotation effect using keyframes at the start and end of the turning motion.

what “missing frames” do you mean? why should there be missing frames?

The missing frames are the ones that have a rotation angle from 0 - 90 degrees. The frames shot while the camera was rotating. Rotating them manually would take more time than writing a python script to correct the rotation angle in each frame, if that is possible, imho.

With could visually check the point in time where the rotation starts and where it ends. Then, for the OpenCV code, calculate the corresponding frame numbers and calculate the rotation for each frame between those, do the rotation and needed cropping (as all frames need to be the same size). Note that OpenCV loses sound in the process, so that must be restored with some other tool.

Of course, a more advanced approach would be to detect some element in the video that should be kept horizontal and rotate accordingly.

You’ll find online plenty example code for reading and writing videos, and rotating an ímage while restoring its size.