A quick Python script to catch the average frame colours of a YouTube video.
I wrote this Python script based as a quick challenge after I saw an example of something similar for various films on Reddit. In true University fashion, I created the first 70% of the script in the first few hours, and then procrastinated for 6 months to finish the rest.
The full solution is available here: https://github.com/ShantnuS/AverageFrameColour
The aim was to make something similar to what I saw on Reddit, which was for films, for any YouTube video. What the script should ideally be able to do is take a URL of a YouTube video, extract the frames and then output an image of the results.
The way I approached this was:
- Find a way to download a YouTube video (as it is probably easier to work with a video you have downloaded)
- Find a way to extract a frame from that video from a given time stamp – I knew I could use some mathematics (😎) to find a method to extract frames at a regular interval (i.e. a loop)
- Find a way to find the average colour of an image (the frame from the video)
- Find a way to draw the average colour and output the result as an image
To download the video: I found a library called Pytube that allows you to input a URL and download the video as an mp4 in a given folder.
To extract the frames from the video and get the average colours: I used the following script and created a list of average colours. The Pillow library was extremely useful in this.
To draw the image: once again the Pillow library was used. By creating a new image of the width of the average colour array and drawing lines of that colour, this step was quite easy.
An example output of the script is shown below. The example is from the trailer of the horror film Us, and shows how the trailer starts off bright and descends into darkness – much like the movie.
Feel free to copy, extend and improve the script as you wish. The method I used was probably not the most efficient, so do let me know of any improvements you make!
Thanks for your blog, nice to read. Do not stop.
Thank you!