Why my code just writes the last variable?

Viewed 56

The code below should make 10 videos with names 1,2,3,..., 10 but it just writes the last video and other videos are 0 kb. I am not sure where is the problem. The code is reproducible.


import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from cv2 import VideoWriter, VideoWriter_fourcc

pixels = 600
my_dpi = 100
num_geo=10
FPS=1
seconds = 100

load_x = np.random.rand(14,100,3)
coord = np.random.rand(5,2,10)


for i in range(num_geo):
    fourcc = VideoWriter_fourcc(*'MP42')
    video = VideoWriter((str(i) + ".mp4"), fourcc, FPS, (pixels, pixels))
    
for j in range(100):
    fig = plt.figure(num_geo,figsize=( pixels/my_dpi,  pixels/my_dpi),facecolor='k', dpi=my_dpi)  
    plt.axes([0,0,1,1])
    rectangle = plt.Rectangle((-300, -300), 600, 600, fc='k')
    plt.gca().add_patch(rectangle)
    a=load_x[0,j,:].tolist()
    a=matplotlib.colors.to_hex(a)

    plt.plot([coord[0][0][i], coord[4][0][i]], [coord[0][1][i], coord[4][1][i]], color=str(a), lw=8, antialiased=True)
    plt.axis('off')
    plt.axis([-300,300,-300,300])
        
    fig.canvas.draw()
    
    data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
    data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))   
 
    video.write(data)
video.release()
1 Answers

Indent the second loop and all subsequent lines.

EDIT: you should probably pull a bunch of unnecessary calculations outside the second for loop as well. See updated version below:

for i in range(num_geo):
    fourcc = VideoWriter_fourcc(*'MP42')
    video = VideoWriter((str(i) + ".mp4"), fourcc, FPS, (pixels, pixels))
    fig = plt.figure(num_geo,figsize=( pixels/my_dpi, pixels/my_dpi),facecolor='k', dpi=my_dpi)  
    plt.axes([0,0,1,1])
    for j in range(100):
        rectangle = plt.Rectangle((-300, -300), 600, 600, fc='k')
        plt.gca().add_patch(rectangle)
        a=load_x[0,j,:].tolist()
    a=matplotlib.colors.to_hex(a)

    plt.plot([coord[0][0][i], coord[4][0][i]], [coord[0][1][i], coord[4][1][i]], color=str(a), lw=8, antialiased=True)
    plt.axis('off')
    plt.axis([-300,300,-300,300])
            
    fig.canvas.draw()
        
    data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
        data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))   
    
    video.write(data)
    video.release()
Related