代码:
# 将image对应的txt文件复制到对应路径
def img_txt(img_file, old_path, output_path):
# 获取图像列表
list_image = os.listdir(img_file)
for image in list_image:
# 获得文件名称
(name, extension) = os.path.splitext(image)
# 旧文件所在目录
old = os.path.join(old_path, name + '.txt')
# 要存放的新文件
new = os.path.join(output_path, name + '.txt')
# 复制
shutil.copy(old, new)
文件重命名
def rename_file(file_path, output_path):
file_txt = os.listdir(file_path)
for txt in file_txt:
(name, path) = os.path.splitext(txt)
(txt_name,extension) = os.path.splitext(name)
src = os.path.join(file_path, name + '.txt')
dsc = os.path.join(output_path, txt_name + '.txt')
os.rename(src, dsc)
# 保存txt文件对应的mask文件
def read_file(txt_file, mask_file, output_path):
file_name = os.listdir(txt_file)
for file in file_name:
(name,extension) = os.path.splitext(file)
img = os.path.join(mask_file, name)
(pic_,exten) = os.path.splitext(name)
img_str = Image.open(img).convert('L')
# 指定输出txt文件路径
path = os.path.join(output_path, f"{pic_}.txt")
# 存储到指定路径
img_str.save(path)