python pictures copied to the specified folder according to label classification

After the test folder under the picture were kmeans clustering (k here I will set 7), get a txt file. txt file has two columns, a first column corresponding to the picture belongs to the category, the second column is the distance from the centroid of the image. As shown:
Here Insert Picture Description
Now I built a 0-6 seven folder, and then copy the images to a different folder by category, detailed code is as follows:

import numpy as np
import os
import shutil

# 读取txt文件并将其转化为array
f = open(r"./result.txt")
line = f.readline()
data_list = []
while line:
    num = list(map(float, line.split(',')))
    data_list.append(num)
    line = f.readline()
f.close()
data_array = np.array(data_list)
# print(data_array[:,0])

# 读取每张图片按照其分类复制到相应的文件夹中
imgs = os.listdir('./test')
imgnum = len(imgs)  # 文件夹中图片的数量
j = 1
for i in range(imgnum):  # 遍历每张图片
    # print(int(data_array[i][0]))
    label=int(data_array[i][0])    #图片对应的类别
    shutil.move('./test/'+str(j)+'.jpg', './'+str(label)+'/'+str(j)+'.jpg')
    j+=1

Here used shutil.move () function, the images from one file to another folder. The first parameter is the old file path, and the second parameter is the new file path.

Guess you like

Origin blog.csdn.net/hnu_zzt/article/details/84885843