为什么我的代码只写最后一个变量?

Why my code just writes the last variable?

下面的代码应该制作 10 个名称为 1,2,3,...,10 的视频,但它只写入最后一个视频,其他视频为 0 kb。我不确定问题出在哪里。代码是可重现的。


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()

缩进第二个循环和所有后续行。

编辑:您可能还应该在第二个 for 循环之外进行一些不必要的计算。请参阅下面的更新版本:

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()