【问题标题】:How can I rename Images in subdirectories?如何重命名子目录中的图像?
【发布时间】:2019-12-22 17:15:26
【问题描述】:

我创建了一个用于训练神经网络的合成图像数据集。每个图像文件夹都有一个“图像”文件夹和一个“蒙版”文件夹。 不幸的是,“图像”文件夹中的图像名称不正确。

├── img995
│   ├── images
│   │   └── img142.png
│   └── masks
│       ├── img10_mask10_.png
│       ├── img10_mask10.png

我的目标是重命名“图像”文件夹中的图像(而不是遮罩文件夹中的图像)。

我试过这段代码,但它没有按预期工作:

import os
os.getcwd()
collection = "/home/dataset/"

for imi in os.listdir(collection):
    for images, masks in imi:
        for p in images:
            os.rename(collection + p + images,
                      collection + p + str(995 + i) + ".png")
Error message:

      4 for imi in os.listdir(collection):
----> 5     for images, masks in imi:
      6         for p in images:
      7             os.rename(collection + p + images,

ValueError: not enough values to unpack (expected 2, got 1)

【问题讨论】:

  • 我不能 100% 确定您想要的输出到底是什么(为什么是 701?),但对我来说,glob.glob 可能对您的任务有用 docs.python.org/3/library/glob.html
  • 如果你看一下“示例树”:img142.png 应该重命名为 img995.png。

标签: python operating-system filesystems


【解决方案1】:
import os
os.getcwd()
collection = "/home/dataset/"

for imi in os.listdir(collection): # Lists all files and folders
    path = '{0}{1}'.format(collection, imi)
    if(os.path.isdir(path)): # Filter by folders
        folder_number = imi[3:] # Collect folder number
        image_folder = '{0}/images'.format(path) # Collect image folder
        for image in os.listdir(image_folder): # Collect image in image folder
            image_path = '{0}/{1}'.format(image_folder, image) # Build original image path
            new_image = 'img{0}.png'.format(folder_number) # New image file name
            new_image_path = '{0}/{1}'.format(image_folder, new_image) # Build new image path
            os.rename(image_path, new_image_path) # Rename image with folder number

按照您的示例树结构,这将重命名

├── imgX
│   ├── images
│   │   └── imgY.png    <-- This File 
│   └── masks
│       ├── img10_mask10_.png
│       ├── img10_mask10.png

├── imgX
│   ├── images
│   │   └── imgX.png  <-- This File
│   └── masks
│       ├── img10_mask10_.png
│       ├── img10_mask10.png

对于home/dataset/ 中的所有img 文件夹

【讨论】:

  • 有很多好的解决方案,但是这个很容易理解。谢谢
【解决方案2】:

我对您的要求有点困惑,但是如果您想将_new 添加到image 文件夹中的所有图像,您可以使用以下内容:

for root, dirs, files in os.walk('dataset'):
    if os.path.basename(root) == 'images':
        for f in files:
            name, ext = os.path.splitext(f)
            os.rename(os.path.join(root, f), os.path.join(root, name + '_new' + ext))

【讨论】:

    【解决方案3】:

    我认为这可以解决您的问题:

    import os
    first_list = [name for name in os.listdir("/home/dataset/") if name.endswith(".png")]
    # if you want to rename and enumerate your images
    final = [str(x[0])+'_new_name.png' for x in enumerate(first_list)]
    
    # if you don't want to enumerate and just rename them
    final = ['new_name.' + x.split('.')[1] for x in first_list]
    

    祝你好运!

    【讨论】:

      【解决方案4】:

      glob 可以成为你的朋友。基本上,如果您只想遍历 png 子文件夹下的所有 png 文件,您可以这样做:

      import os
      import glob
      
      collection = "/home/dataset"
      
      generic_pattern = os.path.join(
          collection,
          "*", "images", "*.png"
      )
      
      for a_file in glob.glob(generic_pattern):
          f_path, f_name = os.path.split(a_file)
          f_raw_name, f_ext = f_name.split('.')
          # not sure what you want to do for the new file name
          new_name = f_path.split(os.sep)[-2]  # would be 'img995' in the example
          f_new = os.path.join(
              f_path, 
              '{0}.{1}'.format(new_name, f_ext)
          )
          # to see what you will be doing:
          print(a_file, f_new)
          # if everything works fine, uncomment this:
          # os.rename(a_file, f_new)
      

      【讨论】:

      • 您可以随时使用f_path.split('/')[-2][3:] 访问imgX 文件夹号
      猜你喜欢
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 2015-04-27
      • 2017-12-30
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      相关资源
      最近更新 更多