Skip to content

Instantly share code, notes, and snippets.

@hahouari
Last active November 5, 2022 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hahouari/9e5e0a779f577dbef88ecc881a1089d1 to your computer and use it in GitHub Desktop.
Save hahouari/9e5e0a779f577dbef88ecc881a1089d1 to your computer and use it in GitHub Desktop.
Detect video rotation using ffmpeg and cv2 in python
import ffmpeg
def get_rotation(video_file_path: str):
try:
# fetch video metadata
metadata = ffmpeg.probe(video_file_path)
except Exception as e:
print(f'failed to read video: {video_file_path}\n'
f'{e}\n',
end='',
flush=True)
return None
# extract rotate info from metadata
video_stream = next((stream for stream in metadata['streams'] if stream['codec_type'] == 'video'), None)
rotation = int(video_stream.get('tags', {}).get('rotate', 0))
# extract rotation info from side_data_list, popular for Iphones
if len(video_stream.get('side_data_list', [])) != 0:
side_data = next(iter(video_stream.get('side_data_list')))
side_data_rotation = int(side_data.get('rotation', 0))
if side_data_rotation != 0:
rotation -= side_data_rotation
return rotation
import cv2
def get_rotation_code(video_file_path: str):
rotation = get_rotation(video_file_path)
rotation_code = None
if rotation == 180:
rotation_code = cv2.ROTATE_180
if rotation == 90:
rotation_code = cv2.ROTATE_90_CLOCKWISE
if rotation == 270:
rotation_code = cv2.ROTATE_90_COUNTERCLOCKWISE
return rotation_code

Tested using:

  • ffprobe version 4.4.2-0ubuntu0.22.04.1.
  • ffmpeg-python==0.2.0 package from pip.
  • (Optional, for get_rotation_code()) opencv-contrib-python==4.6.0.66 package from pip.

get_rotation is intentionally separated for those not using opencv. Another note: this code expects given file to always have one stream that has codec_type to be video, if your use case might have otherwise (example of audio only files), modify the code to handle such exceptions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment