如何重命名子目录中的图像?

2024-06-09 08:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个用于训练神经网络的合成图像数据集。每个图像文件夹都有一个“images”文件夹和一个“masks”文件夹。 很遗憾,“images”文件夹中的图像名称不正确。你知道吗

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

我的目标是重命名“images”文件夹中的图像(而不是masks文件夹中的图像)。你知道吗

我尝试了此代码,但没有按预期工作:

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)

Tags: in图像文件夹forpngos神经网络collection
3条回答

我对您的要求有点困惑,但是如果您想将_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))

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

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]

祝你好运!你知道吗

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文件夹

相关问题 更多 >