如何使用Python批量保存matplotlib pyplot生成的自定义椭圆图像?
实现批量保存的方法
你可以直接通过两种方式实现自动化批量保存,不需要手动操作:
方法1:直接保存原始64×64椭圆图像(推荐用于数据集制作)
这种方式保存的图像没有Matplotlib自带的坐标轴、边框等冗余元素,是纯原始像素的图像,最适合作为训练数据集使用。
首先如果需要永久保存文件到你的Google Drive,先运行挂载代码:
from google.colab import drive drive.mount('/content/drive') import os # 自定义保存文件夹路径,不存在会自动创建 save_path = "/content/drive/MyDrive/ellipse_dataset" os.makedirs(save_path, exist_ok=True)
不需要永久保存的话可以把路径替换为Colab临时路径/content/ellipse_dataset,生成后可以在左侧文件栏打包下载。
修改你的循环代码如下,可直接生成并保存指定数量的图像:
import numpy as np import cv2 import pandas as pd # 此处可以修改为你需要的图像数量,比如64或者100 total_num = 100 # 可选:同步保存椭圆参数作为标签 label_list = [] for i in range(total_num): img = np.full((64,64,3), 255, dtype=np.uint8) center_x = np.random.randint(30,45) center_y = np.random.randint(30,45) major_axis = np.random.randint(1,9) minor_axis= np.random.randint(1,9) angle = 0 # 绘制椭圆 cv2.ellipse(img, (center_x, center_y), (major_axis, minor_axis), angle, 0, 360, (0, 0, 0), -1) # 保存图像 filename = f"ellipse_{i}.png" cv2.imwrite(f"{save_path}/{filename}", img) # 保存参数到标签列表 label_list.append({ "filename": filename, "center_x": center_x, "center_y": center_y, "major_axis": major_axis, "minor_axis": minor_axis }) # 保存标签文件到同目录 pd.DataFrame(label_list).to_csv(f"{save_path}/labels.csv", index=False)
方法2:保存Matplotlib绘制的带显示效果的图像
如果你需要保留Matplotlib的显示样式(比如坐标轴、边框),可以用plt.savefig方法,每次循环记得清空画布避免内容重叠:
import numpy as np import cv2 from matplotlib import pyplot as plt import os save_path = "/content/drive/MyDrive/ellipse_plt_dataset" os.makedirs(save_path, exist_ok=True) total_num = 100 for i in range(total_num): # 清空上一次循环的画布 plt.clf() img = np.full((64,64,3), 255, dtype=np.uint8) center_x = np.random.randint(30,45) center_y = np.random.randint(30,45) major_axis = np.random.randint(1,9) minor_axis= np.random.randint(1,9) angle = 0 cv2.ellipse(img, (center_x, center_y), (major_axis, minor_axis), angle, 0, 360, (0, 0, 0), -1) plt.imshow(img) # 保存当前画布 plt.savefig(f"{save_path}/ellipse_plt_{i}.png", dpi=100)
内容的提问来源于stack exchange,提问作者contactbibliophile
相关产品推荐
相关产品推荐

