Как отсортировать файлы изображений в две папки на основе имени файла из списка в Python? - PullRequest
1 голос
/ 20 марта 2019

У меня есть папка с изображениями собак с именем dogID-X.jpg, где X - номер изображения, принадлежащего одному dogID, например, 0a08e-1.jpg, 0a08e-2.jpg, 0a08e-3.jpgозначает, что есть три изображения, которые принадлежат одной и той же собаке.Как отсортировать эти изображения в две подпапки на основе двух списков, которые имеют только dogID [0a08e, 4a45t, ...], то есть все изображения с идентификаторами из одного списка должны попадать в одну папку, а все изображения из другого списка - вдругая папка.Спасибо!Список выглядит так: list(y_labels) = ['86e1089a3', '6296e909a', '5842f1ff5', '850a43f90', 'd24c30b4b', '1caa6fcdb', ...]

for image in list(y_labels):
              folder = y_labels.loc[image, 'PetID']
              old = './train_images/{}'.format(image)
              new = '//train_images_new/{}/{}'.format(folder, image)
  try:
    os.rename(old, new)
  except:
    print('{} - {}'.format(image,folder))

Ответы [ 4 ]

1 голос
/ 20 марта 2019
import os
import shutil 
path = r'C:\Users\user\temp\test\dog_old' #folder where all dog images present
list_name =[]
# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk(path):
    list_name.extend(files)

from collections import defaultdict

dic=defaultdict(list)



for i in list_name:
    filename,ext =os.path.splitext(i)
    group, img_index = filename.split('-')
    dic[group].append(img_index)

# folder path where new  dog images had to added
new_folder = r'C:\Users\user\temp\test\dog_new'

for i in dic:        
        if not os.path.exists(os.path.join(new_folder,i)):
            os.mkdir(os.path.join(new_folder,i))
            for img in dic[i]:
                old_image = os.path.join(path,'{}-{}.jpg'.format(i,img))
                new_image = r'{}.jpg'.format(img)
                new_path =os.path.join(new_folder,i)

                shutil.move(old_image,os.path.join(new_path,new_image))
        else:
            for img in dic[i]:
                old_image = os.path.join(path,'{}-{}.jpg'.format(i,img))
                new_image = r'{}.jpg'.format(img)
                new_path =os.path.join(new_folder,i)
                print(new_path)
                shutil.move(old_image,os.path.join(new_path,new_image))
0 голосов
/ 20 марта 2019

Хорошо, давайте предположим, что у вас есть 2 списка lis1 и lis2, содержащие только dogID, есть также папка, которая содержит все изображения, и я назову ее «mypath», подпапки будут называться «lis1» и «lis2»..

import os

# path to image folder, get all filenames on this folder
# and store it in the onlyfiles list

mypath = "PATH TO IMAGES FOLDER"
onlyfiles = [f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]

# your list of dogID's
lis1 = ["LIST ONE"]
lis2 = ["LIST TWO"]

# create two seperate lists from onlyfiles list based on lis1 and lis2
lis1files = [i for i in onlyfiles for j in lis1 if j in i]
lis2files = [i for i in onlyfiles for j in lis2 if j in i]

# create two sub folders in mypath folder
subfolder1 = os.path.join(mypath, "lis1")
subfolder2 = os.path.join(mypath, "lis2")

# check if they already exits to prevent error
if not os.path.exists(subfolder1):
    os.makedirs(subfolder1)

if not os.path.exists(subfolder2):
    os.makedirs(subfolder2)

# move files to their respective sub folders
for i in lis1files:
    source = os.path.join(mypath, i)
    destination = os.path.join(subfolder1, i)
    os.rename(source, destination)

for i in lis2files:
    source = os.path.join(mypath, i)
    destination = os.path.join(subfolder2, i)
    os.rename(source, destination)

Надеюсь, это решит вашу проблему.

0 голосов
/ 20 марта 2019

Попробуйте это,

import os
pet_names = ['0a08e', '0a08d']
image_ids =  ["0a08e-1.jpg", "0a08e-2.jpg", "0a08e-3.jpg","0a08d-1.jpg", "0a08d-2.jpg", "0a08d-3.jpg"]

image_folder_path = os.getcwd()#"<image folder path>"
# assuming you want to name the folder with the pet name, create folders with the names in the list.
for pet_name in pet_names:
    if not os.path.exists(os.path.join(image_folder_path,pet_name)):
        print("creating")
        os.makedirs(pet_name)
# loop over the image id's match the pet name and put it in the respective folder
for img_id in image_ids:
    for pet_name in pet_names:
        if pet_name in img_id:
                image_full_path_source = os.path.join(image_folder_path,img_id)

                dest_path = os.path.join(image_folder_path,pet_name)

                image_full_path_destination = os.path.join(dest_path,img_id)

                os.rename(image_full_path_source, image_full_path_destination)

Надеюсь, это поможет!

0 голосов
/ 20 марта 2019

Для этого вы можете использовать шутил . Просто используйте dst в качестве места назначения файла, куда он должен идти, основываясь на списке.

from shutil import copyfile

copyfile(src, dst)

Я могу предоставить дополнительную помощь, если вы покажете свой код, который вы написали до сих пор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...