No1:需求:有原始图片,需要生成对应名称的标签文件,并且每个图片的每个标签文件内容一样。
如图,根据左图生成右图,且写入图片内容内容。
No2:代码实现:
import osroot_dir = r'F:\data\dataset\hymenoptera_data\hymenoptera_data\train'ant_dir = 'ants_image' #蜜蜂原图路径ant_label = 'ants_label' #蜜蜂标签路径bees_dir = 'bees_image' #蚂蚁原图路径bee_label = 'bees_label' #蚂蚁标签路径# 制作ant标签文件,每个标签里面写ants类别def make_ant_label():img_name = [] # 存放图片的名字for i in os.listdir(os.path.join(root_dir, ant_dir)):img_name.append(i.split('.')[0]) #只取名字for img in img_name:with open(os.path.join(root_dir, ant_label, f'{img}.txt'), mode='w', encoding='utf-8') as f:f.write("ants") #向文件里面写标签内容print("ant label make end!")# 制作bee标签文件,每个标签里面写bees类别。def make_bee_label():img_name = [] # 存放图片的名字for i in os.listdir(os.path.join(root_dir, bees_dir)):img_name.append(i.split('.')[0]) #只取名字for img in img_name:with open(os.path.join(root_dir, bee_label, f'{img}.txt'), mode='w', encoding='utf-8') as f:f.write("bees") #向文件里面写内容print("bees label make end!")if __name__ == '__main__':make_ant_label()make_bee_label()