我如何才能使这段代码仅适合一个具有160个子文件夹的文件夹?

问题描述

import numpy as np
import os
import matplotlib.pyplot as plt

path = r"E:/work/dataset"
dir_list = next(os.walk(path))[1]
dir_list.sort()

true_image,false_image = [],[]
for directory in dir_list:
    images = os.listdir(path+directory)
    images.sort()
    images = [path+directory+'/'+x for x in images]
    true_image.append(images[:30]) # First 30 images in each folder are true
    false_image.append(images[30:]) # Next 24 images are fake

真实图像还有160个文件夹,每个文件夹包含30张图像。

# Quick check to confirm we have data of all the 160 individuals
len(true_image),len(false_image)

true_lengths = [len(x) for x in true_image]
false_lengths = [len(x) for x in false_image]
print(true_lengths)
print(false_lengths)

true_train,true_val,true_test = true_image[:120],true_image[120:140],true_image[140:]
false_train,false_val,false_test = false_image[:120],false_image[120:140],false_image[140:]
# All the images will be converted to the same size before processing
img_h,img_w = 155,220
def visualize_sample_images():
    '''Function to randomly select a signature from train set and
    print two genuine copies and one forged copy'''
    fig,(ax1,ax2,ax3) = plt.subplots(1,3,figsize = (10,10))
    k = np.random.randint(len(true_train))
    true_img_names = random.sample(true_train[k],2)
    false_img_name = random.sample(false_train[k],1)
    true_img1 = cv2.imread(true_img_names[0],0)
    true_img2 = cv2.imread(true_img_names[1],0)
    false_img = plt.imread(false_img_name[0],0)
    true_img1 = cv2.resize(true_img1,(img_w,img_h))
    true_img2 = cv2.resize(true_img2,img_h))
    false_img = cv2.resize(true_img,img_h))

    ax1.imshow(true_img1,cmap = 'gray')
    ax2.imshow(true_img2,cmap = 'gray')
    ax3.imshow(false_img,cmap = 'gray')

    ax1.set_title('true copy')
    ax1.axis('off')
    ax2.set_title('true copy')
    ax2.axis('off')
    ax3.set_title('False copy')
    ax3.axis('off')
visualize_sample_images()

我正在使用以下代码。但是我只使用true_images。此代码用于两个文件夹。我已尽力使它仅适合一个文件夹,但是我得到的输出为空

print(true_length)

visualize_sample_images()

请建议我对代码进行一些更改以使其适合一个。我想将true_images文件夹划分为true_test,true_train,true_val。真实图片内部有160个子文件夹,每个文件夹包含30张真实图片

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)