Is there a way in python to get the dimensions of a video file or some other library that would accomplish th开发者_如何学JAVAis? The equivalent of a Media Info
or something? Thank you.
If I understood you correctly, you mean the resolution of a video for example (768x432).
This could be done simply using opencv in python.
import cv2
file_path = "./video.avi" # change to your own video path
vid = cv2.VideoCapture(file_path)
height = vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
width = vid.get(cv2.CAP_PROP_FRAME_WIDTH)
How about using ffmpeg-python:
import ffmpeg
probe = ffmpeg.probe(movie_path)
video_streams = [stream for stream in probe["streams"] if stream["codec_type"] == "video"]
It gives you a very nice output like this:
>>> import pprint
>>> pprint.pprint(video_streams[0])
{'avg_frame_rate': '30/1',
'bit_rate': '3291',
'bits_per_raw_sample': '8',
'chroma_location': 'left',
'codec_long_name': 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10',
'codec_name': 'h264',
'codec_tag': '0x31637661',
'codec_tag_string': 'avc1',
'codec_time_base': '1/60',
'codec_type': 'video',
'coded_height': 240,
'coded_width': 320,
'color_primaries': 'bt709',
'color_range': 'tv',
'color_space': 'bt709',
'color_transfer': 'bt709',
'display_aspect_ratio': '4:3',
'disposition': {'attached_pic': 0,
'clean_effects': 0,
'comment': 0,
'default': 1,
'dub': 0,
'forced': 0,
'hearing_impaired': 0,
'karaoke': 0,
'lyrics': 0,
'original': 0,
'timed_thumbnails': 0,
'visual_impaired': 0},
'duration': '71.833333',
'duration_ts': 6465000,
'field_order': 'progressive',
'has_b_frames': 1,
'height': 240,
'index': 0,
'is_avc': 'true',
'level': 13,
'nal_length_size': '4',
'pix_fmt': 'yuv420p',
'profile': 'Main',
'r_frame_rate': '30/1',
'refs': 1,
'sample_aspect_ratio': '1:1',
'start_pts': 0,
'start_time': '0.000000',
'tags': {'creation_time': '2018-10-26T04:25:07.000000Z',
'handler_name': 'VideoHandler',
'language': 'und'},
'time_base': '1/90000',
'width': 320}
The only downside is that ffmpeg is required, but this should not be a problem in most of the cases.
In my last company we had similar problem and I couldn't find any python library to do this. So I ended up using mediainfo from python, media info also has a command line option and it is very easy to parse the output, so practically your python module which uses media-info will be sufficient. It has further advantage because eventually you will find all media-info type software doesn't support all codecs/format so you can use multiple software/libs under the hood with single python wrapper.
This library seems to have an example that does just that on its main page (print_info(vs)
):
http://code.google.com/p/ffvideo/
It's a wrapper around ffmpeg (there seems to be a few Python libraries for using ffmpeg).
You could use a pure Python tool hachoir-metadata
:
#!/usr/bin/env python
"""Get dimensions of a video file.
Usage: get-video-dimensions <video-file>
"""
import sys
from itertools import chain
from hachoir_core.cmd_line import unicodeFilename
from hachoir_metadata import extractMetadata
from hachoir_parser import createParser
if len(sys.argv) != 2:
sys.exit(__doc__)
file_metadata = extractMetadata(createParser(unicodeFilename(sys.argv[1])))
print("%sx%s" % next((metadata.get('width'), metadata.get('height'))
for metadata in chain([file_metadata], file_metadata.iterGroups())
if metadata.has('width') and metadata.get('height')))
To install:
$ pip install hachoir-{core,parser,metadata}
There is a python module called pymediainfo - https://pypi.org/project/pymediainfo/ You can use this to get the required metadata of the media file.
Create a directory
mkdir supportfiles
For some reasons I install the module in target directory called "supportfiles"
pip install pymediainfo -t supportfiles/
To get the dimension/resolution of the video file
resolution.py
from supportfiles.pymediainfo import MediaInfo
media_info = MediaInfo.parse('/home/sathish/Videos/Aandipatti.mp4')
for track in media_info.tracks:
if track.track_type == 'Video':
print ("Resolution {}x{}".format(track.width, track.height))
Here is the output
[sathish@localhost test]$ python3.6 resolution.py
Resolution 1920x1080
Just in case if you want to know the list of metadata attributes, Here is the solution
attributes.py
from supportfiles.pymediainfo import MediaInfo
media_info = MediaInfo.parse('/home/sathish/Videos/Aandipatti.mp4')
print(media_info.tracks)
for track in media_info.tracks:
if track.track_type == 'Video':
print(track.to_data().keys())
elif track.track_type == 'Audio':
print(track.to_data().keys())
elif track.track_type == 'General':
print(track.to_data().keys())
else:
print("No metadata present! or probably file corrupt!")
Here is the list of the attributes
[sathish@localhost test]$ python3.6 attributes.py
[<Track track_id='None', track_type='General'>, <Track track_id='1', track_type='Video'>, <Track track_id='2', track_type='Audio'>]
dict_keys(['track_type', 'count', 'count_of_stream_of_this_kind', 'kind_of_stream', 'other_kind_of_stream', 'stream_identifier', 'count_of_video_streams', 'count_of_audio_streams', 'video_format_list', 'video_format_withhint_list', 'codecs_video', 'audio_format_list', 'audio_format_withhint_list', 'audio_codecs', 'complete_name', 'folder_name', 'file_name', 'file_extension', 'format', 'other_format', 'format_extensions_usually_used', 'commercial_name', 'format_profile', 'internet_media_type', 'codec_id', 'other_codec_id', 'codec_id_url', 'codecid_compatible', 'codec', 'other_codec', 'codec_extensions_usually_used', 'file_size', 'other_file_size', 'duration', 'other_duration', 'overall_bit_rate', 'other_overall_bit_rate', 'frame_rate', 'other_frame_rate', 'frame_count', 'stream_size', 'other_stream_size', 'proportion_of_this_stream', 'headersize', 'datasize', 'footersize', 'isstreamable', 'file_last_modification_date', 'file_last_modification_date__local', 'writing_application', 'other_writing_application'])
dict_keys(['track_type', 'count', 'count_of_stream_of_this_kind', 'kind_of_stream', 'other_kind_of_stream', 'stream_identifier', 'streamorder', 'track_id', 'other_track_id', 'format', 'format_info', 'format_url', 'commercial_name', 'format_profile', 'format_settings', 'format_settings__cabac', 'other_format_settings__cabac', 'format_settings__reframes', 'other_format_settings__reframes', 'internet_media_type', 'codec_id', 'codec_id_info', 'codec', 'other_codec', 'codec_family', 'codec_info', 'codec_url', 'codec_cc', 'codec_profile', 'codec_settings', 'codec_settings__cabac', 'codec_settings_refframes', 'duration', 'other_duration', 'duration_firstframe', 'other_duration_firstframe', 'bit_rate', 'other_bit_rate', 'width', 'other_width', 'height', 'other_height', 'stored_height', 'sampled_width', 'sampled_height', 'pixel_aspect_ratio', 'display_aspect_ratio', 'other_display_aspect_ratio', 'rotation', 'frame_rate_mode', 'other_frame_rate_mode', 'frame_rate', 'other_frame_rate', 'minimum_frame_rate', 'other_minimum_frame_rate', 'maximum_frame_rate', 'other_maximum_frame_rate', 'frame_count', 'resolution', 'other_resolution', 'colorimetry', 'color_space', 'chroma_subsampling', 'other_chroma_subsampling', 'bit_depth', 'other_bit_depth', 'scan_type', 'other_scan_type', 'interlacement', 'other_interlacement', 'bits__pixel_frame', 'stream_size', 'other_stream_size', 'proportion_of_this_stream', 'color_range', 'colour_description_present', 'color_primaries', 'transfer_characteristics', 'matrix_coefficients'])
dict_keys(['track_type', 'count', 'count_of_stream_of_this_kind', 'kind_of_stream', 'other_kind_of_stream', 'stream_identifier', 'streamorder', 'track_id', 'other_track_id', 'format', 'format_info', 'commercial_name', 'format_profile', 'codec_id', 'codec', 'other_codec', 'codec_family', 'codec_cc', 'duration', 'other_duration', 'bit_rate_mode', 'other_bit_rate_mode', 'bit_rate', 'other_bit_rate', 'channel_s', 'other_channel_s', 'channel_positions', 'other_channel_positions', 'channellayout', 'samples_per_frame', 'sampling_rate', 'other_sampling_rate', 'samples_count', 'frame_rate', 'other_frame_rate', 'frame_count', 'compression_mode', 'other_compression_mode', 'stream_size', 'other_stream_size', 'proportion_of_this_stream', 'default', 'other_default', 'alternate_group', 'other_alternate_group'])
Hope this will be useful!
The video module in Pygame should work.
You can also get the dimensions directly from the windows metadata:
import win32com.client
def get_dimensions(path,file):
sh = win32com.client.gencache.EnsureDispatch('Shell.Application', 0)
ns = sh.NameSpace(path)
item = ns.ParseName(file)
height = ns.GetDetailsOf(item,314)
width = ns.GetDetailsOf(item,316)
return [height, width]
dimensions = get_dimensions("C:\folder","video.avi")
To get a full overview of available attributes, you can try:
attributes_list = []
for i in range(330):
attributes_list.append([ns.GetDetailsOf("",i), ns.GetDetailsOf(item,i)])
print(attributes_list)
Old question but... To get the size of a file:
file_size_in_Mio = os.path.getsize(name_of_video) //(1024*1024)
精彩评论