matplotlib 使用3D阵列的3D Flutter 绘图视频

62o28rlo  于 2023-05-01  发布在  Flutter
关注(0)|答案(1)|浏览(322)

我试图创建一个3d quiver plot的速度矢量,使用3个数组,其中包含了x,y,z空间中相对于时间的矢量。即箭袋图的视频。有人能帮忙吗?我已经显示了下面的错误消息从运行代码,因为它是。
例如,输出的一帧应该看起来有点像这样:

主代码:第1部分和第2部分。也在这里:
(Note此代码已成功用于2D版本,现在正在升级到3D)

  1. print("Rendering 'Nucleation and Motion in G gradient in 3D'")
  2. print("Lattice constant dx = {}, time step dt = {}".format(fluid_model_g.dx, fluid_model_g.dt))
  3. for n in progressbar.progressbar(range(args.num_frames)):
  4. fluid_model_g.step()
  5. for _ in range(20):
  6. indices = tf.cast(flow_particles, 'int32')
  7. for index in indices.numpy():
  8. flow_streaks[index[0], index[1]] += 0.15 / args.oversampling
  9. dx = tf.gather_nd(fluid_model_g.u, indices)
  10. dy = tf.gather_nd(fluid_model_g.v, indices)
  11. dz = tf.gather_nd(fluid_model_g.w, indices)
  12. flow_particles = (flow_particles + tf.stack([dx, dy, dz], axis=1) * 400) % x.shape
  13. if n % args.oversampling == 0:
  14. rgb = [
  15. tf.reduce_mean((7*fluid_model_g.G)**2, axis=2) + flow_streaks,
  16. tf.reduce_mean((4*fluid_model_g.Y)**2, axis=2),
  17. tf.reduce_mean((2*fluid_model_g.X)**2, axis=2),
  18. ]
  19. frame = make_video_frame(rgb)
  20. writer.append_data(frame)
  21. flow_streaks *= 0
  22. flow_particles = tf.constant(flow_particle_origins, dtype='float64')
  23. #-------------------BJD 22.4.2021----additional rough code at present-----------------------------------------
  24. if n == 200:
  25. print("n = ", n)
  26. break
  27. c1 = c1 + 1
  28. nx, ny, nz = 240, 426, 426
  29. x1 = range(nx)
  30. y1 = range(ny)
  31. z1 = range(nz)
  32. U = np.loadtxt("/home/brendan/runs/tf2-model-g_3d_vel_vector/tf2-model-g/arrays/quiver3D_array31/u.txt")
  33. V = np.loadtxt("/home/brendan/runs/tf2-model-g_3d_vel_vector/tf2-model-g/arrays/quiver3D_array31/v.txt")
  34. W = np.loadtxt("/home/brendan/runs/tf2-model-g_3d_vel_vector/tf2-model-g/arrays/quiver3D_array31/w.txt")
  35. X1, Y1, Z1 = np.meshgrid(x1, y1, z1)
  36. fig = plt.figure(figsize=(10,10))
  37. ax = fig.gca(projection='3d')
  38. ax.set_title("pivot='mid'; every 10th arrow; units='velocity vector' time=" + str(c1))
  39. Q = ax.quiver(X1[::10, ::10, ::10], Y1[::10, ::10, ::10], Z1[::10, ::10, ::10], U[::10, ::10, ::10],
  40. V[::10, ::10, ::10], W[::10, ::10, ::10], pivot='mid', units='inches')
  41. Q.set_array(np.random.rand(np.prod(x.shape))) # may need this? BJD 22.4.2021
  42. ax.scatter(X1[::10, ::10, ::10], Y1[::10, ::10, ::10], Z1[::10, ::10, ::10], color='c', s=0)
  43. plt.tight_layout()
  44. plt.savefig('/home/brendan/runs/tf2-model-g_3d_vel_vector/tf2-model-g/plots/3D_video37/3D_video_velocity_' + str(c1) + '.png')

运行代码时出现错误消息:

  1. brendan@DL380pGen8:~/runs/tf2-model-g_3d_vel_vector/tf2-model-g$ python3 render_video.py /home/brendan/runs/tf2-model-g_2/tf2-model-g/nucleation_3D___3d_velocity_vector__1_seed__y0_x0_____R12_res160pVD20_OS1_ST20___TEST_8th_160.mp4 --params params/nucleation_3D.yaml
  2. 2021-04-22 16:44:29.517603: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
  3. 2021-04-22 16:44:29.517657: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
  4. 2021-04-22 16:44:43.078155: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
  5. 2021-04-22 16:44:43.079068: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory
  6. 2021-04-22 16:44:43.079095: W tensorflow/stream_executor/cuda/cuda_driver.cc:326] failed call to cuInit: UNKNOWN ERROR (303)
  7. 2021-04-22 16:44:43.079164: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (DL380pGen8): /proc/driver/nvidia/version does not exist
  8. 2021-04-22 16:44:43.081520: I tensorflow/compiler/jit/xla_gpu_device.cc:99] Not creating XLA devices, tf_xla_enable_xla_devices not set
  9. Rendering 'Nucleation and Motion in G gradient in 3D'
  10. Lattice constant dx = 0.15, time step dt = 0.041666666666666664
  11. N/A% (0 of 480) | | Elapsed Time: 0:00:00 ETA: --:--:--2021-04-22 16:44:46.312362: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:126] None of the MLIR optimization passes are enabled (registered 2)
  12. 2021-04-22 16:44:46.335468: I tensorflow/core/platform/profile_utils/cpu_utils.cc:112] CPU Frequency: 1994870000 Hz
  13. Traceback (most recent call last):
  14. File "render_video.py", line 855, in <module>
  15. episodes[args.episode](writer, args)
  16. File "render_video.py", line 647, in nucleation_3D
  17. fluid_model_g.step()
  18. File "/home/brendan/runs/tf2-model-g_3d_vel_vector/tf2-model-g/fluid_model_g.py", line 284, in step
  19. np.savetxt("/home/brendan/runs/tf2-model-g_3d_vel_vector/tf2-model-g/arrays/quiver3D_array31/u.txt", self.u) # BJD 22.4.2021
  20. File "<__array_function__ internals>", line 5, in savetxt
  21. File "/usr/local/lib/python3.8/dist-packages/numpy/lib/npyio.py", line 1371, in savetxt
  22. raise ValueError(
  23. ValueError: Expected 1D or 2D array, got 3D array instead
  24. brendan@DL380pGen8:~/runs/tf2-model-g_3d_vel_vector/tf2-model-g$
u5rb5r59

u5rb5r591#

我不得不记录一个2D Flutter 图一段时间回来。
我使用的方法是:
1.创建要使用的图形。
1.将fig转换为图像(numpy数组)
1.使用opencv-pythoncv2)写入输出。

Fig to arr

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import io
  4. def fig_to_numpy(fig, dpi=180):
  5. """
  6. Converts an input Figure, to a numpy array.
  7. If used by Matplotlib, this will close the figure.
  8. :param fig: plt.figure
  9. The input figure, with all items drawn onto it.
  10. :param dpi: int
  11. The resolution of the output image, keep in mind that larger
  12. takes longer.
  13. :return: np.ndarray
  14. Return a numpy array containing the figure images.
  15. """
  16. buf = io.BytesIO()
  17. fig.tight_layout()
  18. fig.savefig(buf, format="png", dpi=dpi)
  19. plt.close(fig=fig)
  20. buf.seek(0)
  21. img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
  22. buf.close()
  23. img = cv2.imdecode(img_arr, 1)
  24. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  25. return img

录音

这是一个录音类的例子,有许多替代选项(examples)。

  1. class Record:
  2. def __init__(self, output, size, fps=20., format='mp4v'):
  3. fourcc = cv2.VideoWriter_fourcc(*format)
  4. self.out = cv2.VideoWriter(output, fourcc, fps, size[::-1])
  5. def __enter__(self):
  6. return self
  7. def __exit__(self, exc_type, exc_val, exc_tb):
  8. self.close()
  9. def add(self, frame):
  10. if not self.out.isOpened():
  11. raise RuntimeError(f"Video is already closed.")
  12. self.out.write(frame)
  13. def show(self, frame, delay=1):
  14. cv2.imshow('Recording', frame)
  15. cv2.waitKey(delay)
  16. def close(self):
  17. self.out.release()
  18. cv2.destroyWindow('Recording')

测试用例

这生成(假)测试图像。

  1. def quiver_plot(data, time: int):
  2. """ Create a fake quiver plot. """
  3. fig = plt.figure(figsize=(10, 10))
  4. ax = fig.gca(projection='3d')
  5. ax.set_title("pivot='mid'; every 10th arrow; units='velocity vector' time=" + str(time))
  6. ax.scatter(*data, color='c', s=0)
  7. return fig
  8. def quiver_data(time):
  9. x, y, z = np.meshgrid(np.arange(0.2, 1, 0.2 * time), np.arange(0.2, 1, .2 * time), np.arange(0.2, 1, .8))
  10. u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
  11. v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
  12. w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) * np.sin(np.pi * z))
  13. return u, v, w

测试代码

  1. if __name__ == '__main__':
  2. # Get size of figure
  3. data = quiver_data(time=1)
  4. fig = quiver_plot(data, time=1)
  5. arr = fig_to_numpy(fig)
  6. with Record(output='test.mp4', size=arr.shape[:2], fps=1) as writer:
  7. for time in tqdm.trange(1, 11):
  8. data = quiver_data(time)
  9. fig = quiver_plot(data, time)
  10. arr = fig_to_numpy(fig)
  11. writer.add(arr)
  12. writer.show(arr, delay=1)
展开查看全部

相关问题