Python Newb Code Snippets #18
86-Get Video File Info
This heavily Shambleized snippet could easily be used as a function inside any code that deals with videos files. It gives some limited information about the loaded video file.
I just cobbled this code together from ‘how to’ fragments found in various places.
First it strips the base name from the path, leaving just the loaded video’s file name. Then using Opencv we find out the frame rate, and the total amount of frames in the video.
Next we get the video’s duration in minutes and seconds. I liked the use of modulus to work out the seconds, as I actually get it, yes, I actually understand a mathematical thingy at last.
The code also delivers the width and height of the video. No great Python breakthrough in coding excellence here I know, but a worthy snippet for beginners or for reference.
Unfortunately the only bit of worthwhile information it doesn’t deliver is the codecs used for the audio and video. That was my failure, I just couldn’t work it out, but I got close, and I promise I will add codec info to the code as soon as I suss it out.
If you want to do it yourself as an exercise then here is a stack overflow post that gives a few possibilities.
Isn’t it refreshing to know that someone as dumb as Shambles can write blog posts like this and be honest about how incompetent he is? . Gen Pub.
Hmm Gen, I wouldn’t insult my readers’ intelligence by pretending I know much about anything really, thanks lol.
All the following code snippets work on both Windows and Linux.
pip install opencv-python
Double click inside code box to select all.
''' 86-Get video file info pip install opencv-python Tested on Windows 7 and Linux Mint ''' import os import cv2 # Load a video. video_in = 'test.mp4' # Get file name, no path. file_name = os.path.basename(video_in) # Get frame rate. vid_cap = cv2.VideoCapture(video_in) vid_fps = int(vid_cap.get(cv2.CAP_PROP_FPS)) # Find total frames. frame_count = int(vid_cap.get(cv2.CAP_PROP_FRAME_COUNT)) # Duration. vid_duration = frame_count/vid_fps vid_minutes = int(vid_duration/60) vid_seconds = round(vid_duration%60) #The % is Modulus, ie.remainder # Get height and width of video. vid_height = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) vid_width = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # Output the collected info. print() print('File name:', file_name) print('Duration: '+str(vid_minutes) +'M:'+str(vid_seconds)+'s') print('FPS:', vid_fps) print('Total frames:', frame_count) print('Dimensions: '+str(vid_width)+' X '+str(vid_height)) print()
87-Demux Audio From A Video
This snippet separates the audio from a video file and saves it out as a mp3 file, or whatever format you want. If, for example, you want the audio saved as an aac file then in the code below (the second last line) just change the -f option from mp3 to aac and audio.mp3 to audio.aac. Useful if you want to rip music from a downloaded YouTube video for example.
The following snippets, (I hesitate to call them code), require the download and installation of FFmpeg on your machine first. It’s simple enough to install, it’s small, and is a worthwhile addition to any OS, totally free of course.
On Linux Mint, just type this into terminal and it installs no problem:
sudo apt-get install ffmpeg
For Windows, go to ffmpeg.org and download and run installer.
If you look at the colossal amount of things FFmpeg can do, in what is in effect, one line of code, you will see why I have a zealous interest in this.
I have only just realised what a fantastic piece of software FFmpeg is. Typically I discovered it whilst researching the finishing touches of code snippet 86. I soon realised that FFmpeg can do all those things and more, but I had spent too much time on snippet 86 to bin it
The reason I hesitate to call this code is that we are going to cheat and just send the equivalent of a Dos\terminal command to FFmpeg to do job for us, using the subprocess module, which is part of the standard library, so no pip install required for that.
Because I felt guilty about ‘code cheating’, I added a open file dialog to help select the video file. Rather pathetic I know, but what can I do?
Initially I could not get the Python FFmpeg commands to work on Linux. I thought it had something to do with the shell, the way the command is sent, or a path problem.
I managed to finally get snippet 90 working on Linux by using the .split() function on the command, but it didn’t seem to help for the other three for some reason.
To cut a long story short, after a whole day of googling and experimenting I almost gave up. FFmpeg always reported a file not found error.
Just as I was about to say b*****ks to it, these are Windows only, I realised that the error was only printing some of the path of the file not found. I was running the code from deep inside several folders, uh huh. I ran the code from inside one folder and they all worked, (with .split() added). Doh!
If you are wondering what use demuxing could be, then I can assure you it can be very useful in Python, in fact this is ripped from my forth-coming Auto Video colorizer app.
In AVC I had to demux the audio from the source video and remux it to the finished colourized video, (opencv doesn’t do audio), and it works, surprisingly! I am hoping my next post on this blog will be to unveil Auto Video Colourizer, but I can’t be sure yet.
As far as FFmpeg goes, you will most likely have already used it, it is the backbone of almost every video and audio converter. Maybe we can make out own little apps using FFmpeg and a GUI? There’s a zillion possibilities with this one.
''' 87-Demux audio from a video Tested on Linux Mint and Windows 7 Requires ffmpeg installed on system. free from ffmpeg.org linux:sudo apt-get install ffmpeg ''' import subprocess from tkinter import filedialog, Tk # Hide naff unwanted window. ROOT = Tk() ROOT.withdraw() # User loads a video, via file dialog. VIDEO = filedialog.askopenfilename(title="Load a video", filetypes=[(("All files", "*.*"))]) # If sucessful, the file audio.mp3 will be saved # in the current working directory. ff_command = "ffmpeg -y -i "+str(VIDEO)+" -vn -f mp3 audio.mp3" subprocess.Popen(ff_command.split())
I will give a brief explanation here of what each of the options in the FFmpeg line do, but there are so many possibilities that you can change that you really need to scour the FFmpeg docs for more detailed info.
The -y tells FFmpeg to allow overwriting of files. If we didn’t do this then a dos window pops up for an ‘overwrite y\n’ input. if you prefer to remove the -y option then no problem, the code will still work.
The -i option prints out some information to the console, I don’t think we need this, but the code wouldn’t work for me when I tried to remove it.
The -vn means do not include video stream in output.
The -f signals which file format you want, mp3 in our case.
You can also add the -ab option if you want. It stands for audio bitrate, example, -ab 128
you should put it before the -f option. -ab can be any bitrate you want, commons bitrates are 128, 160, 190, 320.
88-Remux Audio Back Onto A Video
This is how we remux the audio back onto the original, or any other, video. I have saved some space by not repeating the Tk file dialog, but if you did want it you can easily copy and paste it from previous the code.
''' 88-Remux audio back onto a video Tested omn Linux Mint and Windows 7 ''' import subprocess # load a video file. VIDEO = "test.mp4" # load a sound file. SOUND = "sound.mp3" # Mux audio back again. save_name = "muxed.avi" ff_comm = "ffmpeg -y -i "+str(VIDEO)+" -i "+str(SOUND)+" -c copy -map 0:v -map 1:a "+str(save_name) subprocess.Popen(ff_comm.split())
89-Convert To Almost Any Video Format
I have cut this code to absolute minimum, just to show three ways of doing the same thing, and to stop myself getting bored.
As is clear in the code comments. Your video named infile.avi (or change it to whatever name and format you want, (example, test.mp4), will be converted to outfile.wmv or change the wmv to avi, mp4 or any video format you can think of.
''' 89-Convert to almost any video format ''' import subprocess # Change infile.avi to your source video. # Change outfile.wmv to destination video. ff_comm = "ffmpeg -y -i infile.avi -c:v libx264 outfile.wmv" subprocess.Popen(ff_comm.split())
90-Convert To Almost Any Audio Format
And now for audio conversion.
''' 90-Convert to almost any audio format ''' import subprocess ff_comm = "ffmpeg -y -i yourfile.aac newfilename.mp3" subprocess.Popen(ff_comm.split())
Resources:
five-ffmpeg-commands-every-video-geek-should-know-about
ffmpeg-commands-media-file-conversions
That’s all for now. I will be back as soon as I can with Snippets #19.
Here are my other snippets:
Snippets #1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11, #12 ,#13, #14 ,#15 ,#16 and #17
You can get all my source code snippets and projects from my Dropbox folder.
Using Python V3.6.5 32bit, on Windows 7 64bit
and Python V3.67 on Linux Mint 19.1 Cinnamon 64bit
Previous Post: Auto Photo Colorizer
from Python Coder
via read more
No comments:
Post a Comment