3D Video with Python

In this article, I will take you through an excellent technique to create a 3D video with python by using the matplotlib package. But before learning to create a 3D video with python, I would suggest you learn how to create 3D plots with python from here.

3D Video with Python using Matplotlib

First, I’ll create a simple 3D contour plot with matplotlib:

Also, Read – How to use Machine Learning in Marketing?

The code above will give you a digit without an axis because we are declaring axis3don = False. We cannot hide the panel and grid colour, but we can make it similar to the background image (white) as mentioned in the comment “# make the panel and grid colour “white”. The code will display the result like this:

image for post

A video is a collection of images. We are therefore going to create many images with different azimuthal axis viewpoints. We can adjust this:

# adjust point of view
ax.view_init(60, 90)Code language: CSS (css)

Now, we need to change the value of 90 to a sequence number from 0 to 360 by using the code below:

You will get 180 images with different names, you can check it in Jupyter Notebook 3d directory by using the command below:

! ls 3d/

The names of the images are listed from 3d_vis_0.png to 3d_vis_358_.png. To combine them all, we need to create an array consisting of the names of figures, using the code below:

from PIL import Image
png_count = 180
files = []
for i in range(png_count):
    seq = str(i*2)
    file_names = '3d_vis_'+ seq +'.png'
    files.append(file_names)
    
print(files)Code language: JavaScript (javascript)

Then we combine all of that into a single video to create a 3D video with Python. The extension of the video is in GIF. You combine it using the code below:

# Create the frames
frames = []
files
for i in files:
    new_frame = Image.open(i)
    frames.append(new_frame)
    
# Save into a GIF file that loops forever   
frames[0].save('3d_vis.gif', format='GIF',
               append_images=frames[1:],
               save_all=True,
               duration=40, loop=0)Code language: PHP (php)

It will save to a GIF file named 3d_vis.gif that is 40 seconds long in a single loop. Here is the output of the modified 3D video. I just modified the angle and colour maps:

3D video

I hope you liked this article on how you can create a 3D video with Python using Matplotlib. Feel free to ask your valuable questions in the comments section below.

Also, Read – NumPy Broadcasting in Python.

Follow Us:

Thecleverprogrammer
Thecleverprogrammer
Articles: 76

Leave a Reply