Python 根据标签移动图片

Python move pictures based on label

我有一个包含数百张图片的文件夹,名称为

Picture_1_001.png,  
Picture_1_003.png
Picture_1_010.png
Picture_1_012.png
Picture_1_014.png
and so on

我有一个 table 看起来像这样:

Col_1             Col_2
Picture_1_001.png 0
Picture_1_003.png 0
Picture_1_010.png 1
Picture_1_012.png 2
Picture_1_014.png 3
...

我想做的是使用shutil.copy()功能,将Col_2="0"的图片移动到文件夹0,将Col_2="1"的图片移动到文件夹1 ].

我所做的是:

import os
import numpy as np
import shutil

isExists = os.path.exists(r'./0')

if not isExists:
    os.makedirs((r'./0'))
    os.makedirs(r'./1')
    os.makedirs(r'./2')
 

txt_file = pd.read_csv(r"./results.txt", sep = '\t',header=None)
txt_file
Col_1 Col_2
Picture_1_001.png 0
Picture_1_003.png 0
Picture_1_010.png 1
Picture_1_012.png 2
Picture_1_014.png 3
...


data_list = []
for index, rows in txt_file.iterrows():
    # Create list for the current row
    my_list =[rows.Col_1, rows.Col_2]
      
    # append the list to the final list
    data_list.append(my_list)

data_array = np.array(data_list)

source_dir ='./picture'
img = os.listdir(source_dir)

imgnum = len(img) 

for i in range(imgnum):
    label=int(data_array[i][1]) 
    print(label)

for fileNum in img:
    if not os.path.isdir(fileNum):
        imgName = os.path.join(source_dir,fileNum) 
        (imgPath, tempimagName) = os.path.split(imgName) 
        (shotname,extension) = os.path.splitext(tempimagName) 

    tempimagName='%s.png'%shotname
    imgName=os.path.join('./picture/',tempimagName)
    shutil.copy(imgName,'./'+str(label)+'/'+tempimagName)

这使得所有图片都进入同一个文件夹而不是拆分。如何分割我的照片?

以下部分有问题:

for i in range(imgnum):
    label=int(data_array[i][1]) 
    print(label)

因为您正在为标签设置最终值并在最后一个循环中使用它。您也可以为标签使用迭代器,并在复制行中使用它。

以下可能不是执行此操作的最佳方法,但您可以理解:

label = []
for i in range(imgnum):
    label.append(int(data_array[i][1]))

i=0
for fileNum in img:
    if not os.path.isdir(fileNum):
        imgName = os.path.join(source_dir,fileNum) 
        (imgPath, tempimagName) = os.path.split(imgName) 
        (shotname,extension) = os.path.splitext(tempimagName) 
    
    lbl = str(label[i])
    i+=1
    
    tempimagName='%s.png'%shotname
    imgName=os.path.join('./picture/',tempimagName)
    shutil.copy(imgName,'./'+lbl+'/'+tempimagName)